Created
June 9, 2018 18:25
-
-
Save epequeno/26832a9fc69d3921a790ffcc45e9c402 to your computer and use it in GitHub Desktop.
fibonacci with memoization and big integers
This file contains hidden or 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
extern crate num_bigint; | |
use num_bigint::{BigUint, ToBigUint}; | |
use std::collections::HashMap; | |
fn fibo(n: BigUint, memo: &mut HashMap<BigUint, BigUint>) -> BigUint { | |
let zero = 0.to_biguint().unwrap(); | |
let one = 1.to_biguint().unwrap(); | |
let two = 2.to_biguint().unwrap(); | |
if n == zero || n == one { | |
return n | |
} | |
if let Some(val) = memo.get(&n) { | |
return val.clone() | |
} | |
let ans = fibo(n.clone()-one, memo) + fibo(n.clone()-two, memo); | |
memo.insert(n, ans.clone()); | |
ans | |
} | |
fn main() { | |
let mut memo: HashMap<BigUint, BigUint> = HashMap::new(); | |
for i in 90..=100 { | |
println!("fibo({}) = {}", i, &mut fibo(i.to_biguint().unwrap(), &mut memo)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment