【递归优化】【斐波那契】

f(n) = f(n-1)+f(n-2)

1,2,3,5,8.....

自顶向下使用的递归层次比较多,在n取值较大的情况下,效率很低(时间维度)

所以可以使用数组来替换多重递归调用,即以空间来置换时间(intersting)

#include <stdio.h>
#include <error.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
 
#define ERROR  -22
 
#define DEBUG	0


static long int feibonaqie_toptolow(int n)
{
	int max = pow(2,(sizeof(int)*8)-1)-1;

	if(n<=0||n>max){
		return ERROR;
	}
	
	if(n==1){
		return 1;
	}
	if(n==2){
		return 2;
	}
	
	long int ret = 0;
	ret = feibonaqie_toptolow(n-1)+feibonaqie_toptolow(n-2);
	return ret;
}

static long int feibonaqie_lowtotop(int n)
{
	int max = pow(2,(sizeof(int)*8)-1)-1;

	if(n<=0||n>max){
		return ERROR;
	}
	
	int i =0;
	long int arr[n];
	arr[1] = 1;
	arr[2] = 2;
	for(i=3; i<=n; i++){
		arr[i] = arr[i-1]+arr[i-2];
	}
	//printf("arr[%d] is %ld\n", i-1, arr[i-1]);
	return arr[i-1];
}


int main()
{
	struct timeval start, end;  
    float timeuse = 0.0;
	gettimeofday(&start, NULL);  
	printf("%ld\n", feibonaqie_toptolow(40));
	gettimeofday(&end, NULL);  
	timeuse = (1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec)/1000.0;  
	printf("time_use is %.2fms\n", timeuse); 
	
	gettimeofday(&start, NULL);  
	printf("%ld\n", feibonaqie_lowtotop(40));
	gettimeofday(&end, NULL);  
	timeuse = (1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec)/1000.0;  
	printf("time_use is %.2fms\n", timeuse); 
}

看一个执行效果:

$ ./a.exe
165580141
time_use is 677.24ms
165580141
time_use is 0.00ms
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值