public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Let's assume that the user input "java Fibonacci 7", so the result would be like this:
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
I seem to be totally confused with how this works, starting with argument 3. When the fib(i) method gets passed 3, shouldn't it return 3 as well since if n = 3 then the sum of fib(n-1) /n-1 is 2/ and fib(n-2) /n-2 is 1/ is 3. And so on the other numbers forward.
This is a much simpler code to generate Fibonacci sequence like '0 1 1 2 3 ...'.
public static void main (String[] args) {
int f = 0;
int g = 1;
for (int i = 1; i <= 10; i++) {
System.out.print(f + " ");
f = f + g;
g = f - g;
}
System.out.println();
}
If you pass 3 to your function it will do the following:
fib(3) = fib(2) + fib(1) //so we we are into the else statement, because 3 > 1
= fib(2) + 1 //fib(1) = 1 because 1 <= 1 so you return it (if statement)
= (fib(1) + fib(0)) + 1 //2 > 1 => we go to the else statement
= (1 + 0) + 1 //0 <= 1 & 1 <= 1 so we are into the if and return the values
= 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With