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.
39 lines
991 B
39 lines
991 B
2 years ago
|
type CZS = Vec<Option<u32>>;
|
||
|
struct Collatz { czs: CZS }
|
||
|
|
||
|
impl Collatz {
|
||
|
pub fn new() -> Collatz {
|
||
|
let cl0 = Some(0); // for indexing
|
||
|
let cl1 = Some(1);
|
||
|
Collatz { czs: vec![cl0, cl1] }
|
||
|
}
|
||
|
pub fn compute(&mut self, n: usize) -> u32 {
|
||
|
match self.ensure_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[n] = Some(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() {
|
||
|
let mut collatz = Collatz::new();
|
||
|
|
||
|
for k in 0..100000usize {
|
||
|
let clk = collatz.compute(k);
|
||
|
println!("{}: {}", k, clk);
|
||
|
}
|
||
|
}
|