Fibonacci Series numbers are 0,
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144…
The first two numbers in the
Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous
two.
I.e. third number + fourth number
= fifth number means 1 + 2 = 3.
To reflect this, I have kept fib
(n-2) + fib (n-1) = fib (n) in my method.
And I am returning same number in
case of 0 and 1 as
series starts with these two numbers.
public class Fibonacci {
public static int fib(int n) {
if (n <= 1) {
return n;
}
return fib(n -
1) + fib(n - 2);
}
public static void main(String[]
args) {
int num = 10;
for (int i = 0; i <=
num; i++)
System.out.println(i + ": " + fib(i));
}
}
plz give explanation of this program how to make it
ReplyDeleteFibonacci Series numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144…
DeleteThe first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.
I.e. third number + fourth number = fifth number means 1 + 2 = 3.
To reflect this, I have kept fib (n-2) + fib (n-1) = fib (n) in my method.
And I am returning same number in case of 0 and 1 as series starts with these two numbers.
So f(0) = 0 , f(1) =1, f(2) = f(1) + f(0), f(3) = f(2) + f(1)….
This comment has been removed by the author.
ReplyDelete