Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Saloni28

macrumors newbie
Original poster
Jun 20, 2022
1
0
Java:
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:

Code:
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.
 

admwright

macrumors regular
Sep 11, 2008
244
54
Scotland
You need to remember that the fib function is recursive, so for 3 you call fib(2)+fib(1) and the call to fib(2) will then call fib(1)+fib(0). fib(1) always returns 1 and fib(0) always returns 0 so you end up with (1+0)+(1) = 2

For 4 it is fib(3)+fib(2) and so end up with (1+0+1)+(1+0) = 3
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.