zoukankan      html  css  js  c++  java
  • 指数级计算复杂度 调用Fibonacci函数次数

    指数级计算复杂度

    计算调用次数

    #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
    请按任意键继续. . .

  • 相关阅读:
    RE_知识回顾
    python网络爬虫边看边学(selenium模块三验证码)
    python网络爬虫边看边学(selenium模块二无头浏览器)
    python网络爬虫边看边学(selenium模块一)
    python爬虫边看边学(多线程多进程协程)
    python爬虫边看边学(xpath模块解析)
    python爬虫边看边学(bs4安装与使用)
    python爬虫边看边学(数据解析)
    python爬虫边看边学(基础)
    python基础结束
  • 原文地址:https://www.cnblogs.com/rsapaper/p/10488818.html
Copyright © 2011-2022 走看看