指数级计算复杂度
计算调用次数
#include <stdio.h> long fibonacciCallTimes(long n); int main(void) { long result,start,end,number; int i; printf("Enter an integer-SATRT:"); scanf("%ld",&start); printf("Enter an integer-END:"); scanf("%ld",&end); for (i=start; i<=end; i++) { number = i; result=fibonacciCallTimes(number); printf("fibonacciCallTimes(%ld)=%ld ",number,result); } return 0; } long fibonacciCallTimes(long n) { /* base case */ if(n==0 || n==1) { return 1; } else { return 1+fibonacciCallTimes(n-1)+fibonacciCallTimes(n-2); } }
Enter an integer-SATRT:0
Enter an integer-END:11
fibonacciCallTimes(0)=1
fibonacciCallTimes(1)=1
fibonacciCallTimes(2)=3
fibonacciCallTimes(3)=5
fibonacciCallTimes(4)=9
fibonacciCallTimes(5)=15
fibonacciCallTimes(6)=25
fibonacciCallTimes(7)=41
fibonacciCallTimes(8)=67
fibonacciCallTimes(9)=109
fibonacciCallTimes(10)=177
fibonacciCallTimes(11)=287
请按任意键继续. . .
分析上边逻辑漏洞
正确答案:
为了计算第n个Fibonacci数,共需要调用fibonacci函数的此时达到2^n数量级。
Enter an integer-SATRT:0
Enter an integer-END:31
Fibonacci(0)=0
Fibonacci(1)=1
Fibonacci(2)=1
Fibonacci(3)=2
Fibonacci(4)=3
Fibonacci(5)=5
Fibonacci(6)=8
Fibonacci(7)=13
Fibonacci(8)=21
Fibonacci(9)=34
Fibonacci(10)=55
Fibonacci(11)=89
Fibonacci(12)=144
Fibonacci(13)=233
Fibonacci(14)=377
Fibonacci(15)=610
Fibonacci(16)=987
Fibonacci(17)=1597
Fibonacci(18)=2584
Fibonacci(19)=4181
Fibonacci(20)=6765
Fibonacci(21)=10946
Fibonacci(22)=17711
Fibonacci(23)=28657
Fibonacci(24)=46368
Fibonacci(25)=75025
Fibonacci(26)=121393
Fibonacci(27)=196418
Fibonacci(28)=317811
Fibonacci(29)=514229
Fibonacci(30)=832040
Fibonacci(31)=1346269
请按任意键继续. . .