//Fibonacci
//F(n) = n; n = 0,1
//F(n) = F(n-1) + F(n-2),n >= 2;
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//递归,效率很低
int64_t fibo1(int n){
if(n<2){
return 1;
}
return ( fibo1(n-1) + fibo1(n-2) );
}
//递归,缓存历史计算值,调用链仍较长
int64_t fibo2_inter(int64_t* arr,int n){
if(n>1){
arr[n]=fibo2_inter(arr,n-1) + arr[n-2];
}
return arr[n];
}
int64_t fibo2(int n){
int64_t num=0;
int64_t* p=(int64_t*)calloc(n+1,sizeof(int64_t));
if(NULL==p){
return -1;
}
p[0]=1;
p[1]=1;
num=fibo2_inter(p,n);
free(p);
p=NULL;
return num;
}
//迭代
int64_t fibo3(int n){
int64_t num0=1;
int64_t num1=1;
int64_t numTmp=1;
if(n<2){
return 1;
}
while(n>1){
numTmp=num1;
num1 += num0;
num0=numTmp;
--n;
}
return num1;
}
int main(int argc,char **argv)
{
if(argc!=3){
printf("./Fibonacci i_way num\n");
return 0;
}
int i_way=atoi(argv[1]);
int n=atoi(argv[2]);
switch(i_way){
case 1:
printf("./Fibonacci fibo1(%d)= %lld\n",n,fibo1(n));
break;
case 2:
printf("./Fibonacci fibo2(%d)= %lld\n",n,fibo2(n));
break;
case 3:
printf("./Fibonacci fibo3(%d)= %lld\n",n,fibo3(n));
break;
default:
break;
}
return 0;
}
斐波那契数列C实现
最新推荐文章于 2024-05-15 14:42:02 发布