Header Ads

Java fibonacci algorithm

Java fibonacci algorithm 

fibonacci


In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:[1][2]

Often, especially in modern usage, the sequence is extended by one more initial term:
.[3]

The sequence Fn of Fibonacci numbers is defined by the recurrence relation:By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

with seed values[1][2]
or[5]



Ex1 Fibonacci recursive:



int Fibonacci(int n){
     if (n <= 1)
         return n;
     return Fibonacci(n-1) + Fibonacci(n-2);
}


Ex2 Fibonacci For:



 //time O(n)
 int fib(int n) {
        int a = 0, b = 1, c;
        if (n == 0)
            return a;
        for (int i = 2; i <= n; i++) {
            c = a + b;
            a = b;
            b = c;
        }
        return b;
 }


No comments