计算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;
}

posted @ 2011-04-20 22:49  wwwwwwwww11we  阅读(178)  评论(0编辑  收藏  举报