11use anyhow:: { Result , anyhow} ;
2- use num:: Integer ;
32use std:: collections:: HashSet ;
43
54fn string_length_of ( n : u64 ) -> u32 {
@@ -20,10 +19,6 @@ fn repeat(n: u64, times: u32) -> u64 {
2019 result
2120}
2221
23- fn postfix_of ( n : u64 , length : u32 ) -> u64 {
24- n % 10_u64 . pow ( length)
25- }
26-
2722fn calculate ( inp : & str ) -> Result < ( u64 , u64 ) > {
2823 let mut p1 = 0 ;
2924 let mut p2 = 0 ;
@@ -37,22 +32,23 @@ fn calculate(inp: &str) -> Result<(u64, u64)> {
3732 . ok_or_else ( || anyhow ! ( "invalid format" ) ) ?;
3833
3934 let start: u64 = start. trim ( ) . parse ( ) ?;
35+ let start_slen = string_length_of ( start) ;
4036 let end: u64 = end. trim ( ) . parse ( ) ?;
4137 let end_slen = string_length_of ( end) ;
4238
43- for n in start..=end {
44- let n_slen = string_length_of ( n) ;
45- for postfix_len in 1 ..=end_slen / 2 {
46- let ( times, remainder) = n_slen. div_mod_floor ( & postfix_len) ;
47- if times < 2 || remainder != 0 {
48- continue ;
49- }
50- let sx = repeat ( postfix_of ( n, postfix_len) , times) ;
39+ for postfix_len in 1 ..=end_slen / 2 {
40+ let times_lower_bound = start_slen / postfix_len;
41+ let times_upper_bound = end_slen / postfix_len;
42+
43+ for postfix in 10_u64 . pow ( postfix_len - 1 ) ..10_u64 . pow ( postfix_len) {
44+ for times in times_lower_bound. max ( 2 ) ..=times_upper_bound {
45+ let n = repeat ( postfix, times) ;
5146
52- if sx >= start && sx <= end {
53- invalid_p2. insert ( sx) ;
54- if times == 2 {
55- invalid_p1. insert ( sx) ;
47+ if n >= start && n <= end {
48+ invalid_p2. insert ( n) ;
49+ if times == 2 {
50+ invalid_p1. insert ( n) ;
51+ }
5652 }
5753 }
5854 }
@@ -105,18 +101,6 @@ mod tests {
105101 assert_eq ! ( repeat( 101 , 3 ) , 101101101 ) ;
106102 }
107103
108- #[ test]
109- fn test_postfix ( ) {
110- assert_eq ! ( postfix_of( 99 , 1 ) , 9 ) ;
111- assert_eq ! ( postfix_of( 10 , 1 ) , 0 ) ;
112- assert_eq ! ( postfix_of( 11 , 1 ) , 1 ) ;
113-
114- assert_eq ! ( postfix_of( 9999 , 2 ) , 99 ) ;
115- assert_eq ! ( postfix_of( 1000 , 2 ) , 0 ) ;
116- assert_eq ! ( postfix_of( 1001 , 2 ) , 1 ) ;
117- assert_eq ! ( postfix_of( 1010 , 2 ) , 10 ) ;
118- }
119-
120104 #[ test]
121105 fn test_string_length ( ) {
122106 assert_eq ! ( string_length_of( 0 ) , 1 ) ;
0 commit comments