-
Notifications
You must be signed in to change notification settings - Fork 21
/
p129.rs
96 lines (81 loc) · 1.97 KB
/
p129.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//! [Problem 129](https://projecteuler.net/problem=129) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use num_integer::Integer;
fn a(n: u64) -> u64 {
if n == 1 {
return 1;
}
let mut x = 1;
let mut k = 1;
loop {
x = (x * 10 + 1) % n;
k += 1;
if x == 0 {
return k;
}
}
}
fn solve() -> String {
let limit = 1000001;
(limit..)
.step_by(2)
.filter(|&n| !n.is_multiple_of(&5))
.find(|&n| a(n) >= limit)
.unwrap()
.to_string()
}
common::problem!("1000023", solve);
#[cfg(test)]
mod tests {
use num_integer::Integer;
mod naive {
use num_bigint::BigUint;
use num_integer::Integer;
use num_traits::{FromPrimitive, One, Zero};
pub fn r(k: u64) -> BigUint {
let mut r: BigUint = Zero::zero();
let ten: BigUint = FromPrimitive::from_u64(10).unwrap();
let one: BigUint = One::one();
for _ in 0..k {
r = &r * &ten + &one;
}
r
}
pub fn a(n: u64) -> u64 {
let n = FromPrimitive::from_u64(n).unwrap();
(1..).find(|&k| r(k).is_multiple_of(&n)).unwrap()
}
}
#[test]
fn naive_r() {
assert_eq!("1".to_string(), naive::r(1).to_string());
assert_eq!("11".to_string(), naive::r(2).to_string());
assert_eq!("111".to_string(), naive::r(3).to_string());
}
#[test]
fn naive_a() {
assert_eq!(6, naive::a(7));
assert_eq!(5, naive::a(41));
}
#[test]
fn cmp_with_naive() {
for n in (1..100).step_by(2) {
if n.is_multiple_of(&5) {
continue;
}
assert_eq!(naive::a(n), super::a(n));
}
}
#[test]
fn a() {
assert_eq!(6, super::a(7));
assert_eq!(5, super::a(41));
}
}