问题
I was calculating the time complexity of this code that prints all Fibonacci numbers from 0 to n. According to what I calculated, the fib()
method takes O(2^n)
and since it is being called i
number of times, so it came out to be O(n*2^n)
. However, the book says it is O(2^n)
. Can anyone explain why the time complexity here will be O(2^n)
?
Here is the code:
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);
}
回答1:
I finally got my answer from my professor and I'll post it here:
According to him: you should not just simply look the for loop iterating from 0 to n, but you must find what are the actual computations by calculating the steps.
fib(1) takes 2^1 steps
fib(2) takes 2^2 steps
fib(3) takes 2^3 steps
..........
fib(n) takes 2^n steps
now adding these:
2^1 + 2^2 + 2^3 + ........+ 2^n = 2^n+1
and ignoring the constant, it is 2^n, hence the time complexity is O(2^n).
回答2:
I think the best way to think about this is with an example.
We know that fib() runs O(2^n) times roughly, and intuitively we think the runtime of allFib() is O(n*2^n) as mentioned in the book. But this is not the case and here's why.
Why O(n * 2^n) is wrong:
if we sub in 3 for n we get 3 * 2^3 which is equal to 2^3 + 2^3 + 2^3. This is obviously wrong because from looking at the code we know the first loop runs 2^1, the second loop runs 2^2 and the third loop runs 2^3 times. So it should be 2^1 + 2^2 + 2^3.
How we get O(2^n):
If we say n = 3 we know that the work combined is 2^1 + 2^2 + 2^3 and this is equal to roughly 2^4 (look at page 630 in the book "Sum of powers of two" to understand why), so you could say the amount of work done is 2^n+1 , however we drop all the constants for big O, so we are left with 2^n.
来源:https://stackoverflow.com/questions/51576734/time-complexity-for-all-fibonacci-numbers-from-0-to-n