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