DEV Community

Discussion on: Challenge: Write the recursive Fibonacci algorithm in a different language.

Collapse
 
avalander profile image
Avalander • Edited

Nice!

Since writing my implementation I've remembered that the parameter i is unnecessary and you can decrease n instead until it's 0.

fn fib_super_fast(n: u64, curr: u64, prev: u64) -> u64 {
  if n <= 0 {
    return curr;
  }

  return fib_super_fast(n - 1, curr + prev, curr);
}

By the way, you didn't set default values for curr and prev, how does that work, do you need to call it with fib_super_fast(n, 1, 0)?

Collapse
 
fxedel profile image
Felix Edelmann

Yes, I do. But I have to use fib_super_fast(n, 1, 1, 0) as my other implementations also begin with 1. The code for calling the fibonacci methods is:

fn main() {
  loop {
    println!("Enter n:");

    let mut n_str = String::new();
    io::stdin().read_line(&mut n_str).expect("Failed to read line");
    let n = user_input_to_int(n_str);

    let t0 = SystemTime::now();
    let fib_super_fast_n = fib_super_fast(n, 1, 1, 0);
    let t1 = SystemTime::now();
    println!("fib_super_fast(n) = {} ({}µs)", fib_super_fast_n, time_difference(t0, t1));

    let t0 = SystemTime::now();
    let fib_fast_n = fib_fast(n);
    let t1 = SystemTime::now();
    println!("fib_fast(n)       = {} ({}µs)", fib_fast_n, time_difference(t0, t1));

    let t0 = SystemTime::now();
    let fib_n = fib(n);
    let t1 = SystemTime::now();
    println!("fib(n)            = {} ({}µs)", fib_n, time_difference(t0, t1));
  }
}