Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci function result confusion

Tags:

java

algorithm

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.

like image 593
Marz Avatar asked Nov 28 '22 21:11

Marz


2 Answers

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();
}
like image 164
januprasad Avatar answered Dec 10 '22 07:12

januprasad


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
like image 24
Alex VII Avatar answered Dec 10 '22 08:12

Alex VII