Skip to content

Instantly share code, notes, and snippets.

@ruohola
Created January 31, 2020 15:31
Show Gist options
  • Save ruohola/d429283ac32e7e325a4d1d2151c8fc41 to your computer and use it in GitHub Desktop.
Save ruohola/d429283ac32e7e325a4d1d2151c8fc41 to your computer and use it in GitHub Desktop.
use num::{Integer, One};
use std::collections::HashMap;
use std::hash::Hash;
fn fib<T>(n: T) -> T
where
T: std::fmt::Debug + Copy + Hash + Integer,
{
fn fib_memory<T>(n: T, memory: &mut HashMap<T, T>) -> T
where
T: std::fmt::Debug + Copy + Hash + Integer,
{
if !memory.contains_key(&n) {
let val = if n <= One::one() {
n
} else {
fib_memory(n - One::one(), memory) + fib_memory(n - One::one() - One::one(), memory)
};
memory.insert(n, val);
}
*memory.get(&n).unwrap()
}
fib_memory(n, &mut HashMap::new())
}
fn main() {
for i in 0..187 as u128 {
println!("fib({}): {}", i, fib(i));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment