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.
47 lines
1.2 KiB
47 lines
1.2 KiB
use std::collections::HashMap; |
|
type CZS = HashMap<u64, u64>; |
|
struct Collatz { czs: CZS, pub max_computed: u64 } |
|
|
|
impl Collatz { |
|
pub fn new() -> Collatz { |
|
let mut res = Collatz { czs: HashMap::new(), max_computed: 1 }; |
|
res.czs.insert(1, 1); |
|
res |
|
} |
|
pub fn compute(&mut self, n: u64) -> u64 { |
|
if n > self.max_computed { self.max_computed = n; } |
|
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!("new best {} -> {}", best_n, best_cl); |
|
} |
|
} |
|
println!("{} -> {}", best_n, best_cl); |
|
println!("max_computed: {}", collatz.max_computed); |
|
|
|
}
|
|
|