Please explain this simple code:
public int fibonacci(int n) { if(n == 0) return 0; else if(n == 1) return 1; else return fibonacci(n - 1) + fibonacci(n - 2);
}I'm confused with the last line especially because if n = 5 for example, then fibonacci(4) + fibonacci(3) would be called and so on but I don't understand how this algorithm calculates the value at index 5 by this method. Please explain with a lot of detail!
937 Answers
12 NextIn fibonacci sequence each item is the sum of the previous two. So, you wrote a recursive algorithm.
So,
fibonacci(5) = fibonacci(4) + fibonacci(3)
fibonacci(3) = fibonacci(2) + fibonacci(1)
fibonacci(4) = fibonacci(3) + fibonacci(2)
fibonacci(2) = fibonacci(1) + fibonacci(0)Now you already know fibonacci(1)==1 and fibonacci(0) == 0. So, you can subsequently calculate the other values.
Now,
fibonacci(2) = 1+0 = 1
fibonacci(3) = 1+1 = 2
fibonacci(4) = 2+1 = 3
fibonacci(5) = 3+2 = 5And from fibonacci sequence 0,1,1,2,3,5,8,13,21.... we can see that for 5th element the fibonacci sequence returns 5.
See here for Recursion Tutorial.
1There are 2 issues with your code:
- The result is stored in int which can handle only a first 48 fibonacci numbers, after this the integer fill minus bit and result is wrong.
- But you never can run fibonacci(50).
The codefibonacci(n - 1) + fibonacci(n - 2)
is very wrong.
The problem is that the it calls fibonacci not 50 times but much more.
At first it calls fibonacci(49)+fibonacci(48),
next fibonacci(48)+fibonacci(47) and fibonacci(47)+fibonacci(46)
Each time it became fibonacci(n) worse, so the complexity is exponential.
The approach to non-recursive code:
double fibbonaci(int n){ double prev=0d, next=1d, result=0d; for (int i = 0; i < n; i++) { result=prev+next; prev=next; next=result; } return result;
} 10 In pseudo code, where n = 5, the following takes place:
fibonacci(4) + fibonnacci(3)
This breaks down into:
(fibonacci(3) + fibonnacci(2)) + (fibonacci(2) + fibonnacci(1))
This breaks down into:
(((fibonacci(2) + fibonnacci(1)) + ((fibonacci(1) + fibonnacci(0))) + (((fibonacci(1) + fibonnacci(0)) + 1))
This breaks down into:
((((fibonacci(1) + fibonnacci(0)) + 1) + ((1 + 0)) + ((1 + 0) + 1))
This breaks down into:
((((1 + 0) + 1) + ((1 + 0)) + ((1 + 0) + 1))
This results in: 5
Given the fibonnacci sequence is 1 1 2 3 5 8 ..., the 5th element is 5. You can use the same methodology to figure out the other iterations.
2You can also simplify your function, as follows:
public int fibonacci(int n) { if (n < 2) return n; return fibonacci(n - 1) + fibonacci(n - 2);
} 3 Recursion can be hard to grasp sometimes. Just evaluate it on a piece of paper for a small number:
fib(4)
-> fib(3) + fib(2)
-> fib(2) + fib(1) + fib(1) + fib(0)
-> fib(1) + fib(0) + fib(1) + fib(1) + fib(0)
-> 1 + 0 + 1 + 1 + 0
-> 3I am not sure how Java actually evaluates this, but the result will be the same.
4 F(n) / \ F(n-1) F(n-2) / \ / \ F(n-2) F(n-3) F(n-3) F(n-4) / \ F(n-3) F(n-4)Important point to note is this algorithm is exponential because it does not store the result of previous calculated numbers. eg F(n-3) is called 3 times.
For more details refer algorithm by dasgupta chapter 0.2
1Most of the answers are good and explains how the recursion in fibonacci works.
Here is an analysis on the three techniques which includes recursion as well:
- For Loop
- Recursion
- Memoization
Here is my code to test all three:
public class Fibonnaci { // Output = 0 1 1 2 3 5 8 13 static int fibMemo[]; public static void main(String args[]) { int num = 20; System.out.println("By For Loop"); Long startTimeForLoop = System.nanoTime(); // returns the fib series int fibSeries[] = fib(num); for (int i = 0; i < fibSeries.length; i++) { System.out.print(" " + fibSeries[i] + " "); } Long stopTimeForLoop = System.nanoTime(); System.out.println(""); System.out.println("For Loop Time:" + (stopTimeForLoop - startTimeForLoop)); System.out.println("By Using Recursion"); Long startTimeRecursion = System.nanoTime(); // uses recursion int fibSeriesRec[] = fibByRec(num); for (int i = 0; i < fibSeriesRec.length; i++) { System.out.print(" " + fibSeriesRec[i] + " "); } Long stopTimeRecursion = System.nanoTime(); System.out.println(""); System.out.println("Recursion Time:" + (stopTimeRecursion -startTimeRecursion)); System.out.println("By Using Memoization Technique"); Long startTimeMemo = System.nanoTime(); // uses memoization fibMemo = new int[num]; fibByRecMemo(num-1); for (int i = 0; i < fibMemo.length; i++) { System.out.print(" " + fibMemo[i] + " "); } Long stopTimeMemo = System.nanoTime(); System.out.println(""); System.out.println("Memoization Time:" + (stopTimeMemo - startTimeMemo)); } //fib by memoization public static int fibByRecMemo(int num){ if(num == 0){ fibMemo[0] = 0; return 0; } if(num ==1 || num ==2){ fibMemo[num] = 1; return 1; } if(fibMemo[num] == 0){ fibMemo[num] = fibByRecMemo(num-1) + fibByRecMemo(num -2); return fibMemo[num]; }else{ return fibMemo[num]; } } public static int[] fibByRec(int num) { int fib[] = new int[num]; for (int i = 0; i < num; i++) { fib[i] = fibRec(i); } return fib; } public static int fibRec(int num) { if (num == 0) { return 0; } else if (num == 1 || num == 2) { return 1; } else { return fibRec(num - 1) + fibRec(num - 2); } } public static int[] fib(int num) { int fibSum[] = new int[num]; for (int i = 0; i < num; i++) { if (i == 0) { fibSum[i] = i; continue; } if (i == 1 || i == 2) { fibSum[i] = 1; continue; } fibSum[i] = fibSum[i - 1] + fibSum[i - 2]; } return fibSum; }
}Here are the results:
By For Loop 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
For Loop Time:347688
By Using Recursion 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Recursion Time:767004
By Using Memoization Technique 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Memoization Time:327031Hence we can see memoization is the best time wise and for loop matches closely.
But recursion takes the longest and may be you should avoid in real life. Also if you are using recursion make sure that you optimize the solution.
2This is the best video I have found that fully explains recursion and the Fibonacci sequence in Java.
This is his code for the sequence and his explanation is better than I could ever do trying to type it out.
public static void main(String[] args)
{ int index = 0; while (true) { System.out.println(fibonacci(index)); index++; }
} public static long fibonacci (int i) { if (i == 0) return 0; if (i<= 2) return 1; long fibTerm = fibonacci(i - 1) + fibonacci(i - 2); return fibTerm; } For fibonacci recursive solution, it is important to save the output of smaller fibonacci numbers, while retrieving the value of larger number. This is called "Memoizing".
Here is a code that use memoizing the smaller fibonacci values, while retrieving larger fibonacci number. This code is efficient and doesn't make multiple requests of same function.
import java.util.HashMap;
public class Fibonacci { private HashMap<Integer, Integer> map; public Fibonacci() { map = new HashMap<>(); } public int findFibonacciValue(int number) { if (number == 0 || number == 1) { return number; } else if (map.containsKey(number)) { return map.get(number); } else { int fibonacciValue = findFibonacciValue(number - 2) + findFibonacciValue(number - 1); map.put(number, fibonacciValue); return fibonacciValue; } }
} 0 in the fibonacci sequence, the first two items are 0 and 1, each other item is the sum of the two previous items. i.e:
0 1 1 2 3 5 8...
so the 5th item is the sum of the 4th and the 3rd items.
Michael Goodrich et al provide a really clever algorithm in Data Structures and Algorithms in Java, for solving fibonacci recursively in linear time by returning an array of [fib(n), fib(n-1)].
public static long[] fibGood(int n) { if (n < = 1) { long[] answer = {n,0}; return answer; } else { long[] tmp = fibGood(n-1); long[] answer = {tmp[0] + tmp[1], tmp[0]}; return answer; }
}This yields fib(n) = fibGood(n)[0].
Here is O(1) solution :
private static long fibonacci(int n) { double pha = pow(1 + sqrt(5), n); double phb = pow(1 - sqrt(5), n); double div = pow(2, n) * sqrt(5); return (long) ((pha - phb) / div);
} Binet's Fibonacci number formula used for above implementation. For large inputs long can be replaced with BigDecimal.
A Fibbonacci sequence is one that sums the result of a number when added to the previous result starting with 1.
so.. 1 + 1 = 2 2 + 3 = 5 3 + 5 = 8 5 + 8 = 13 8 + 13 = 21Once we understand what Fibbonacci is, we can begin to break down the code.
public int fibonacci(int n) { if(n == 0) return 0; else if(n == 1) return 1; else return fibonacci(n - 1) + fibonacci(n - 2);
}The first if statment checks for a base case, where the loop can break out. The else if statement below that is doing the same, but it could be re-written like so...
public int fibonacci(int n) { if(n < 2) return n; return fibonacci(n - 1) + fibonacci(n - 2); }Now that a base case is establish we have to understand the call stack.Your first call to "fibonacci" will be the last to resolve on the stack (sequence of calls) as they resolve in the reverse order from which they were called. The last method called resolves first, then the last to be called before that one and so on...
So, all the calls are made first before anything is "calculated" with those results. With an input of 8 we expect an output of 21 (see table above).
fibonacci(n - 1) keeps being called until it reaches the base case, then fibonacci(n - 2) is called until it reaches the base case. When the stack starts summing the result in reverse order, the result will be like so...
1 + 1 = 1 ---- last call of the stack (hits a base case).
2 + 1 = 3 ---- Next level of the stack (resolving backwards).
2 + 3 = 5 ---- Next level of the stack (continuing to resolve).They keep bubbling (resolving backwards) up until the correct sum is returned to the first call in the stack and that's how you get your answer.
Having said that, this algorithm is very inefficient because it calculates the same result for each branch the code splits into. A much better approach is a "bottom up" one where no Memoization (caching) or recursion (deep call stack) is required.
Like so...
static int BottomUpFib(int current) { if (current < 2) return current; int fib = 1; int last = 1; for (int i = 2; i < current; i++) { int temp = fib; fib += last; last = temp; } return fib; } Most of solutions offered here run in O(2^n) complexity. Recalculating identical nodes in recursive tree is inefficient and wastes CPU cycles.
We can use memoization to make fibonacci function run in O(n) time
public static int fibonacci(int n) { return fibonacci(n, new int[n + 1]);
}
public static int fibonacci(int i, int[] memo) { if (i == 0 || i == 1) { return i; } if (memo[i] == 0) { memo[i] = fibonacci(i - 1, memo) + fibonacci(i - 2, memo); } return memo[i];
}If we follow Bottom-Up Dynamic Programming route, below code is simple enough to compute fibonacci:
public static int fibonacci1(int n) { if (n == 0) { return n; } else if (n == 1) { return n; } final int[] memo = new int[n]; memo[0] = 0; memo[1] = 1; for (int i = 2; i < n; i++) { memo[i] = memo[i - 1] + memo[i - 2]; } return memo[n - 1] + memo[n - 2];
} Why this answer is different
Every other answer either:
- Prints instead of returns
- Makes 2 recursive calls per iteration
- Ignores the question by using loops
(aside: none of these is actually efficient; use Binet's formula to directly calculate the nth term)
Tail Recursive Fib
Here is a recursive approach that avoids a double-recursive call by passing both the previous answer AND the one before that.
private static final int FIB_0 = 0;
private static final int FIB_1 = 1;
private int calcFibonacci(final int target) { if (target == 0) { return FIB_0; } if (target == 1) { return FIB_1; } return calcFibonacci(target, 1, FIB_1, FIB_0);
}
private int calcFibonacci(final int target, final int previous, final int fibPrevious, final int fibPreviousMinusOne) { final int current = previous + 1; final int fibCurrent = fibPrevious + fibPreviousMinusOne; // If you want, print here / memoize for future calls if (target == current) { return fibCurrent; } return calcFibonacci(target, current, fibCurrent, fibPrevious);
} It is a basic sequence that display or get a output of 1 1 2 3 5 8 it is a sequence that the sum of previous number the current number will be display next.
Try to watch link below Java Recursive Fibonacci sequence Tutorial
public static long getFibonacci(int number){
if(number<=1) return number;
else return getFibonacci(number-1) + getFibonacci(number-2);
}Click Here Watch Java Recursive Fibonacci sequence Tutorial for spoon feeding
4I think this is a simple way:
public static void main(String[] args) { Scanner input = new Scanner(System.in); int number = input.nextInt(); long a = 0; long b = 1; for(int i = 1; i<number;i++){ long c = a +b; a=b; b=c; System.out.println(c); } }
} RanRag(accepted) answer will work fine but that's not optimized solution until and unless it is memorized as explained in Anil answer.
For recursive consider below approach, method calls of TestFibonacci are minimum
public class TestFibonacci { public static void main(String[] args) { int n = 10; if (n == 1) { System.out.println(1); } else if (n == 2) { System.out.println(1); System.out.println(1); } else { System.out.println(1); System.out.println(1); int currentNo = 3; calFibRec(n, 1, 1, currentNo); } } public static void calFibRec(int n, int secondLast, int last, int currentNo) { if (currentNo <= n) { int sum = secondLast + last; System.out.println(sum); calFibRec(n, last, sum, ++currentNo); } }
} public class febo
{ public static void main(String...a) { int x[]=new int[15]; x[0]=0; x[1]=1; for(int i=2;i<x.length;i++) { x[i]=x[i-1]+x[i-2]; } for(int i=0;i<x.length;i++) { System.out.println(x[i]); } }
} By using an internal ConcurrentHashMap which theoretically might allow this recursive implementation to properly operate in a multithreaded environment, I have implemented a fib function that uses both BigInteger and Recursion. Takes about 53ms to calculate the first 100 fib numbers.
private final Map<BigInteger,BigInteger> cacheBig = new ConcurrentHashMap<>();
public BigInteger fibRecursiveBigCache(BigInteger n) { BigInteger a = cacheBig.computeIfAbsent(n, this::fibBigCache); return a;
}
public BigInteger fibBigCache(BigInteger n) { if ( n.compareTo(BigInteger.ONE ) <= 0 ){ return n; } else if (cacheBig.containsKey(n)){ return cacheBig.get(n); } else { return fibBigCache(n.subtract(BigInteger.ONE)) .add(fibBigCache(n.subtract(TWO))); }
}The test code is:
@Test
public void testFibRecursiveBigIntegerCache() { long start = System.currentTimeMillis(); FibonacciSeries fib = new FibonacciSeries(); IntStream.rangeClosed(0,100).forEach(p -&R { BigInteger n = BigInteger.valueOf(p); n = fib.fibRecursiveBigCache(n); System.out.println(String.format("fib of %d is %d", p,n)); }); long end = System.currentTimeMillis(); System.out.println("elapsed:" + (end - start) + "," + ((end - start)/1000));
}and output from the test is: . . . . . fib of 93 is 12200160415121876738 fib of 94 is 19740274219868223167 fib of 95 is 31940434634990099905 fib of 96 is 51680708854858323072 fib of 97 is 83621143489848422977 fib of 98 is 135301852344706746049 fib of 99 is 218922995834555169026 fib of 100 is 354224848179261915075 elapsed:58,0
Here is a one line febonacci recursive:
public long fib( long n ) { return n <= 0 ? 0 : n == 1 ? 1 : fib( n - 1 ) + fib( n - 2 );
} I could not find a simple one liner with a ternary operator. So here is one:
public int fibonacci(int n) { return (n < 2) ? n : fibonacci(n - 2) + fibonacci(n - 1);
} Just to complement, if you want to be able to calculate larger numbers, you should use BigInteger.
An iterative example.
import java.math.BigInteger;
class Fibonacci{ public static void main(String args[]){ int n=10000; BigInteger[] vec = new BigInteger[n]; vec[0]=BigInteger.ZERO; vec[1]=BigInteger.ONE; // calculating for(int i = 2 ; i<n ; i++){ vec[i]=vec[i-1].add(vec[i-2]); } // printing for(int i = vec.length-1 ; i>=0 ; i--){ System.out.println(vec[i]); System.out.println(""); } }
} in more details
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)); }
}Make it that as simple as needed no need to use while loop and other loop
public class FibonacciSeries { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); for (int i = 0; i <= N; i++) { int result = fibonacciSeries(i); System.out.println(result); } scanner.close(); } private static int fibonacciSeries(int n) { if (n < 0) { return 1; } else if (n > 0) { return fibonacciSeries(n - 1) + fibonacciSeries(n - 2); } return 0; }
} Use while:
public int fib(int index) { int tmp = 0, step1 = 0, step2 = 1, fibNumber = 0; while (tmp < index - 1) { fibNumber = step1 + step2; step1 = step2; step2 = fibNumber; tmp += 1; }; return fibNumber;
}The advantage of this solution is that it's easy to read the code and understand it, hoping it helps
A Fibbonacci sequence is one that sums the result of a number then we have added to the previous result, we should started from 1. I was trying to find a solution based on algorithm, so i build the recursive code, noticed that i keep the previous number and i changed the position. I'm searching the Fibbonacci sequence from 1 to 15.
public static void main(String args[]) { numbers(1,1,15);
}
public static int numbers(int a, int temp, int target)
{ if(target <= a) { return a; } System.out.print(a + " "); a = temp + a; return numbers(temp,a,target);
} Try this
private static int fibonacci(int n){ if(n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2);
} public static long fib(int n) { long population = 0; if ((n == 0) || (n == 1)) // base cases { return n; } else // recursion step { population+=fib(n - 1) + fib(n - 2); } return population;
} Simple Fibonacci
public static void main(String[]args){ int i = 0; int u = 1; while(i<100){ System.out.println(i); i = u+i; System.out.println(u); u = u+i; } }
} 1
12 Next