身上无钱你莫邪

moye's c++ blog

c++求Fiobonacci数列的算法效率比较

斐波那契(Fiobonacci)数列:






算法决定了性能,看两个关于数列的算法,分别用递归和数学公式计算数列:

#include<iostream>
#include
<cmath>
#include
<algorithm>
#include
<ctime>
/*斐波那契数列*/
double fiobnacci(int n){
 
if(n==0return 0;
 
else if(n==1return 1;
 
else  if(n>1return fiobnacci(n-1)+fiobnacci(n-2);
}

double fiobnacci2(int n){
 
return (pow((1+sqrt(5.0))/2,n) - pow((1-sqrt(5.0))/2,n))/sqrt(5.0);
}


分别执行两个函数,并显示一下耗费的时长:
int _tmain(int argc, _TCHAR* argv[])
{    
    
/*效率比较*/
    
int a;
    clock_t start 
= clock();
    
for(int i=1;i<5;++i)
        a
=fiobnacci(35);
    cout
<<a<<" "<<(clock()-start)/CLK_TCK<<endl;

    start 
= clock();
    
for(int i=1;i<5;++i)
        a
=fiobnacci2(35);
    cout
<<a<<" "<<(clock()-start)/CLK_TCK<<endl;

    system(
"pause");
    
return 0;}

运行结果:
9227465 2
9227465 0
Press any key to continue . . .

posted on 2008-12-16 18:38 莫耶 阅读(394) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


公告

导航

<2008年12月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

统计

常用链接

留言簿(3)

随笔档案

友情链接

搜索

最新评论

阅读排行榜

评论排行榜