Tag Archives: Fibonacci term generator

Fibonacci Numbers in Rust

One of the things that always interests me about a new language is the creation of Fibonacci numbers. It’s a great way to practice a language. As such, since I am learning Rust, I made a Fibonacci number generator in rust. Here is the code, if you’re interested:

use std::io;

fn main() {
    loop {
        println!("Enter the term that you want to generate!");

        let mut term = String::new();
        io::stdin().read_line(&mut term)
            .ok()
            .expect("Failed to read line!");

        // convert string to int
        let term: usize = match term.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("Please enter a valid number!");
                continue;
            }
        };

        // Get the fib term
        let mut fib_number = get_fib_term_dynamic(term);
        println!("Dynamic Term number {} is {}",term, fib_number);
        fib_number = get_fib_term_recursive(term);
        println!("Recursive term number {} is {}", term, fib_number);
        

    }
}

fn get_fib_term_recursive(term: usize) -> u32 {
    match term {
        0 =>  0,
        1 =>  1,
        _ => get_fib_term_recursive(term-1) + get_fib_term_recursive(term-2),
    }
}

fn get_fib_term_dynamic(term: usize) -> u32 {
    let mut v = vec![0u32, 1];

    for i in 2..(term+1) {
        let sum = v[i-1] + v[i-2];
        v.push(sum);
    }
    return v[term];
}

#[test]
fn it_works() {
    assert!(get_fib_term_recursive(5) == 5);
    assert!(get_fib_term_recursive(6) == 8);
    assert!(get_fib_term_dynamic(5) == 5);
    assert!(get_fib_term_dynamic(6) == 8);
}

You can also view the gist here

Of course, this code also serves as a great way to show that dynamic programming is a much better way to solve for Fibonacci terms.