Reputation: 11
I tried to solve Fibonacci series problem in rust, but unfortunately it always return me exponent of 2^n. Here is my code:
use std::io;
// Fibonacci Series Number
// F(n) = 1,1,2,3,5,8,13,....(n-1),((n-1)+n)
// where, n >= 0
fn fibo(mut n: u32) -> u32 {
let mut _prev: u32 = 0;
let mut current: u32 = 1;
let mut next: u32 = 1;
let mut sum: u32 = 1;
if n <= 0 {
return 0;
}
if n == 1 || n == 2 {
return 1;
};
if n > 2 {
while n >= 1 {
current = next;
_prev = current;
sum = _prev + current;
next = sum;
n -= 1;
}
next
} else {
return 1;
}
}
fn main() {
println!("Fibo of nth: What is nth?: n --> ");
let mut n = String::new();
io::stdin().read_line(&mut n).expect("Invalid input");
let n: u32 = n
.trim()
.parse()
.expect("Not a number. Please type a number");
let fibo = fibo(n);
println!("Fibo of {n}: {fibo}");
}
Here is the output:
I tried to return next which will be the answer of the nth Fibonacci, but it giving me 2^n every time.
Upvotes: 0
Views: 72
Reputation: 117771
Your update is as follows:
current = next;
_prev = current;
sum = _prev + current;
next = sum;
These don't happen all at the same time, but step by step. So after your first step current = next
, current
is overwritten. Then when you do _prev = current
... _prev
is also equal to next
. Which means sum = _prev + current
is just sum = 2*next
. Then next = sum
is essentially just equivalent to next = 2*next
, which is why you're seeing powers of two.
There is a much simpler update you can do, that also only needs 2 mutable variables, current
and next
:
let sum = current + next;
current = next;
next = sum;
Upvotes: 3