You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.2 KiB

2 years ago
use std::collections::HashMap;
type CZS = HashMap<u64, u64>;
2 years ago
struct Collatz { czs: CZS, pub max_computed: u64 }
2 years ago
impl Collatz {
pub fn new() -> Collatz {
2 years ago
let mut res = Collatz { czs: HashMap::new(), max_computed: 1 };
2 years ago
res.czs.insert(1, 1);
res
2 years ago
}
2 years ago
pub fn compute(&mut self, n: u64) -> u64 {
2 years ago
if n > self.max_computed { self.max_computed = n; }
2 years ago
match self.czs.get(&n) {
Some(cl) => *cl,
2 years ago
None => {
//println!("compute {}", n);
2 years ago
let cl_prev = if n % 2 == 0 {
2 years ago
self.compute(n / 2)
} else {
self.compute(3 * n + 1)
};
2 years ago
self.czs.insert(n, cl_prev + 1);
2 years ago
cl_prev + 1
}
}
}
}
fn main() {
let mut collatz = Collatz::new();
2 years ago
let n = 1_000_000u64;
let mut best_cl = 1;
let mut best_n = 1;
for k in (2..=n).step_by(1) {
2 years ago
let clk = collatz.compute(k);
2 years ago
if clk > best_cl {
best_cl = clk;
best_n = k;
2 years ago
println!("new best {} -> {}", best_n, best_cl);
2 years ago
}
2 years ago
}
2 years ago
println!("{} -> {}", best_n, best_cl);
2 years ago
println!("max_computed: {}", collatz.max_computed);
2 years ago
}