zoukankan      html  css  js  c++  java
  • 计算Fibonacci数的几种算法对比

    #include "MyTimer.h"
    #include
    <iostream>
    #include
    <cmath>

    using namespace std;

    unsigned
    int fib_1(unsigned int n)
    {
    if(n<=1) return n;
    return fib_1(n-1)+fib_1(n-2);
    }

    unsigned
    int fib_2(unsigned int n)
    {
    unsigned
    int f[100];
    int i;
    memset(f,
    0,sizeof(unsigned int));
    f[
    1]=f[2]=1;
    for(i=3;i<100;i++)
    f[i]
    =f[i-1]+f[i-2];
    return f[n];
    }

    unsigned
    int fib_3(unsigned int n)
    {
    if(n<=1) return n;
    unsigned
    int prev=0,next=1,fib;
    for(unsigned int i=2;i<=n;i++)
    {
    fib
    =prev+next;
    prev
    =next;
    next
    =fib;
    }
    return fib;
    }

    unsigned
    int fib_4(unsigned int n)
    {
    double x,y;
    unsigned
    int fib;
    x
    =(1+sqrt(5))/2;
    y
    =(1-sqrt(5))/2;
    fib
    =(pow(x,n)-pow(y,n))/sqrt(5);
    return fib;
    }

    unsigned
    int deMoivreFib (unsigned int n)
    {
    //等同于fib_4
    double x;
    x
    =(1+sqrt(5))/2;
    return ceil(exp(n*log(x)-log(sqrt(5))) - .5);
    }

    int main() {
    int n;
    MyTimer mt;
    while(cin>>n)
    {
    /* mt.Start();
    cout<<fib_1(n)<<" ";
    mt.Stop();
    cout<<"fib_1: "<<mt.costTime<<" us"<<endl;
    */
    mt.Start();
    cout
    <<fib_2(n)<<" ";
    mt.Stop();
    cout
    <<"fib_2: "<<mt.costTime<<" us"<<endl;

    mt.Start();
    cout
    <<fib_3 (n)<<" ";
    mt.Stop();
    cout
    <<"fib_3: "<<mt.costTime<<" us"<<endl;

    mt.Start();
    cout
    <<fib_4 (n)<<" ";
    mt.Stop();
    cout
    <<"fib_4: "<<mt.costTime<<" us"<<endl;

    mt.Start();
    cout
    <<deMoivreFib (n)<<" ";
    mt.Stop();
    cout
    <<"deMoF: "<<mt.costTime<<" us"<<endl;
    }
    return 0;
    }

  • 相关阅读:
    pythoon 学习资源
    cookie -- 添加删除
    前端技能
    jsonp 跨域2
    jsonp 跨域1
    webpy.org
    Flask 学习资源
    pip install flask 安装失败
    弹窗组价
    js中的deom ready执行的问题
  • 原文地址:https://www.cnblogs.com/bl4nk/p/2023007.html
Copyright © 2011-2022 走看看