Skip to content

Instantly share code, notes, and snippets.

@epequeno
Created June 9, 2018 18:25
Show Gist options
  • Save epequeno/26832a9fc69d3921a790ffcc45e9c402 to your computer and use it in GitHub Desktop.
Save epequeno/26832a9fc69d3921a790ffcc45e9c402 to your computer and use it in GitHub Desktop.
fibonacci with memoization and big integers
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