Browse Source

014 ok

master
Coin de Gamma 2 years ago
parent
commit
14b400accb
  1. 34
      014/main.rs

34
014/main.rs

@ -1,15 +1,16 @@
type CZS = Vec<Option<u32>>; use std::collections::HashMap;
type CZS = HashMap<u64, u64>;
struct Collatz { czs: CZS } struct Collatz { czs: CZS }
impl Collatz { impl Collatz {
pub fn new() -> Collatz { pub fn new() -> Collatz {
let cl0 = Some(0); // for indexing let mut res = Collatz { czs: HashMap::new() };
let cl1 = Some(1); res.czs.insert(1, 1);
Collatz { czs: vec![cl0, cl1] } res
} }
pub fn compute(&mut self, n: usize) -> u32 { pub fn compute(&mut self, n: u64) -> u64 {
match self.ensure_get(n) { match self.czs.get(&n) {
Some(cl) => cl, Some(cl) => *cl,
None => { None => {
//println!("compute {}", n); //println!("compute {}", n);
let cl_prev = if n % 2 == 0 { let cl_prev = if n % 2 == 0 {
@ -17,22 +18,27 @@ impl Collatz {
} else { } else {
self.compute(3 * n + 1) self.compute(3 * n + 1)
}; };
self.czs[n] = Some(cl_prev + 1); self.czs.insert(n, cl_prev + 1);
cl_prev + 1 cl_prev + 1
} }
} }
} }
pub fn ensure_get(&mut self, i: usize) -> Option<u32> {
while self.czs.len() <= i { self.czs.push(None); }
self.czs[i]
}
} }
fn main() { fn main() {
let mut collatz = Collatz::new(); let mut collatz = Collatz::new();
for k in 0..100000usize { 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); let clk = collatz.compute(k);
println!("{}: {}", k, clk); if clk > best_cl {
best_cl = clk;
best_n = k;
}
//println!("{}: {}", k, clk);
} }
println!("{} -> {}", best_n, best_cl);
} }

Loading…
Cancel
Save