back

fibonacci

background

The final section of the third chapter of the rust book ends with some suggested exercises. The second of which is to write a program to: “Generate the nth Fibonacci number.”

solution

I’m not going to implement the best fibonacci implementation?. Just the bog standard recursive approach with no memoisation. Reusing the input code from the guessing game again:

use std::io;

fn main() {
    loop {
        println!("Which Fibonacci number would you like?");

        let mut n = String::new();

        io::stdin()
            .read_line(&mut n)
            .expect("Failed to read line");

        let n: i32 = match n.trim().parse() {
            Ok(num) => num,
            Err(_) => continue
        };

        let nth_fib = fib(n);

        println!("Fibonacci {n} is: {nth_fib}");
    }
}

fn fib(n: i32) -> i64 {
    if n == 0 {
        return 1;
    } else if n == 1 {
        return 1;
    } else {
        return fib(n-1) + fib(n-2);
    }
}
mail@jonahv.comrss