Created
January 31, 2020 15:31
-
-
Save ruohola/d429283ac32e7e325a4d1d2151c8fc41 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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