The same question has been asked here: Time complexity for all Fibonacci numbers from 0 to n, but I fail to understand the answer provided.
The following code prints all Fibonacci numbers from 0 to n. What is the time complexity?
void allFib(int n){
for(int i = 0 ; i < n ; i++){
System.out.println(i + ": " + fib(i));
}
}
int fib(int n ){
if(n <= 0) return 0;
else if (n == 1) return 1;
return fib(n-1) + fib(n-2);
}
I don't understand why the time complexity is O(2^n) rather than O(n * 2^n). It has been said that:
fib(1) takes 2^1 steps
...
fib(n) takes 2^n steps
I can't see how this is true, since fib(1) immediately returns 1 based on the else statement, so it should take 1 step. Even if this statement were true, I still can't understand how the time complexity is only O(2^n).