zoukankan      html  css  js  c++  java
  • Fibonacci 数列算法分析

     1 /*************************************************
     2 *  Fibonacci 数列算法分析
     3 *************************************************/
     4 #include<iostream>
     5 #include<stdio.h>
     6 #include<vector>
     7 #include<cmath>
     8 #include<time.h>
     9 using namespace std;
    10 #define Time 1000000
    11 #define N 15
    12 #define Echo printf("result:%d | spend:%.3f
    ",a,(((double)(clock()-start))/1000))
    13 #define For for(int i=1; i<Time; ++i)
    14 /*************************************************
    15 Function:       fibo1 fibo2 fibo3  fibo4
    16 defferent:      1递归 2迭代 3向量 4公式
    17 Description:    斐波那契数列求值
    18 Return:         返回第N项的值
    19 *************************************************/
    20 int fibo1(int n) {
    21     if(n==0)return 0;
    22     if(n==1)return 1;
    23     return fibo1(n-1)+fibo1(n-2);
    24 }
    25 int fibo2(int n) {
    26     int a=0,c;
    27     for(int b=1,i=2; i<=n; ++i)
    28         c=a+b,a=b,b=c;
    29     return c;
    30 }
    31 int fibo3(int n) {
    32     vector<int> v(n+1,0);
    33     v[1]=1;
    34     for(int i=2; i<=n; ++i)
    35         v[i]=v[i-1]+v[i-2];
    36     return v[n];
    37 }
    38 int fibo4(int n) {
    39     return (pow((1+sqrt(5.0))/2,n)-pow((1-sqrt(5.0))/2,n))/sqrt(5.0);
    40 }
    41 
    42 int main() {
    43     int a;
    44 
    45     clock_t start=clock();
    46     For a=fibo1(N);
    47     Echo;
    48 
    49     start=clock();
    50     For a=fibo2(N);
    51     Echo;
    52 
    53     start=clock();
    54     For a=fibo3(N);
    55     Echo;
    56 
    57     start=clock();
    58     For a=fibo4(N);
    59     Echo;
    60 
    61     return 0;
    62 }

    循环次数 100000 ,N 为 10 结果如下  

    循环次数 100000 ,N 为 15 结果如下  

     -循环次数 100000 ,N 为 20 结果如下  

    可以看出递归最为耗时:代码简单易懂

    向量由于做了大量的下标工作,相对来说次之

    公式法再次之(在N=15时,公式法与迭代法性能不确定):公式推导,性能具有良好的稳定性

    迭代最优:编程复杂,效率较高

    以上只是针对本次测试

  • 相关阅读:
    Python中的单例模式——装饰器实现剖析
    HTTP协议中GET和POST的区别(详细描述)
    Mysql:The BLACKHOLE Storage Engine
    Mysql:The ARCHIVE Storage Engine
    Mysql:The CSV Storage Engine
    Mysql:The Memory Storage Engine
    Mysql:The Merge Storage Engine:类【union all】联合视图存储引擎
    .Net Core 3.0全新的sql驱动
    .Net Core 3.0原生Json解析器
    Kubernetes-Service(服务)
  • 原文地址:https://www.cnblogs.com/A--Q/p/6076377.html
Copyright © 2011-2022 走看看