DEV Community

Discussion on: Solving the Fibonacci Sequence

Collapse
 
coreyja profile image
Corey Alexander

Rust Solution

I like doing Fib iteratively cause šŸ¤· So here is my iterative fib, and a version that returns a list of the fib numbers. With the iterative answer that is a pretty simply modification!

fn iter_fib(n: u64) -> u64 {
    let mut x = (0, 1);
    for _ in 0..n {
        x = (x.1, x.0 + x.1);
    }

    return x.0;
}

fn iter_fib_list(n: u64) -> Vec<u64> {
    let mut list = Vec::new();
    let mut x = (0, 1);
    for _ in 0..n {
        list.push(x.0);
        x = (x.1, x.0 + x.1);
    }

    return list;
}

fn main() {
    println!("Fib 50 = {:?}", iter_fib(50));
    println!("Fib List to 50 = {:?}", iter_fib_list(51));
}

play.rust-lang.org/?version=stable...