The Fibonacci series starts 0, 1 and each next number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, … Clarify whether N means “the first N terms” or “all terms up to the value N”. The code below prints the first N terms.
Loop version (O(n) time, O(1) space)
static void printFib(int n) {
long a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
long next = a + b;
a = b;
b = next;
}
}
Recursive version
static long fib(int n) {
if (n < 2) return n; // fib(0)=0, fib(1)=1
return fib(n - 1) + fib(n - 2);
}
// print: for (int i = 0; i < n; i++) System.out.print(fib(i) + " ");
Recursion versus a loop
- Readability: the recursive version reads like the maths definition.
- Time: plain recursion recomputes the same values again and again.
fib(5)callsfib(3)twice andfib(2)three times; the total work grows exponentially (roughly 1.6n). The loop is O(n). - Space: recursion uses a stack frame per call, O(n) deep, and can throw
StackOverflowErrorfor large n. The loop uses O(1). - When recursion fits: problems that are naturally recursive, such as trees, divide and conquer and backtracking.
Memoisation: keep recursion, remove repeated work
static long fibMemo(int n, long[] memo) {
if (n < 2) return n;
if (memo[n] != 0) return memo[n];
return memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
}
Each value is computed once, so time is O(n). This is the simplest example of dynamic programming.
Overflow
long holds Fibonacci numbers up to the 92nd term. Use BigInteger beyond that.
Follow-ups
- Check whether a number is a Fibonacci number.
- Print the series up to a value instead of a count.
- What is tail recursion, and does Java optimise it? (No.)
This answer was written by Debugger’s Space as practice material. See how Wipro hires, step by step, and more Wipro practice questions.