UVa495 - Fibonacci Freeze

本文详细介绍了如何使用C++编程语言动态计算斐波那契数列,并通过预定义的函数实现特定位置数值的输出。通过引入字符串数组和特殊算法,文章展示了在内存中高效存储和操作数列元素的方法,同时利用逆序运算提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>

using namespace std;

char Fib[5001][1100] = {"0","1","1"};

void add(char a[],char b[], char c[])
{
	int len_a = strlen(a),len_b = strlen(b);
	int len_c = len_a > len_b ? len_a : len_b;
	++len_c;
	memset(c,'0',len_c);
	memset(a+len_a,'0',len_c-len_a);
	memset(b+len_b,'0',len_c-len_b);

	int carry = 0,temp = 0,i;
	for (i = 0; i < len_c; ++i)
	{
		temp = a[i] - '0' + b[i] -'0' + carry;
		carry = temp / 10;
		c[i] += temp % 10;
	}
	if (carry > 0)
		c[i] += carry,len_c++;
	for (i = len_c-1; i >= 0 && c[i] == '0'; --i);
	c[i+1] = 0;
	len_c = i+1;
}

int main()
{
	for (int i = 3; i <= 5000; ++i)
	{
		char buf1[1100] = {0},buf2[1100] = {0},buf3[1100] = {0};
		strcpy(buf1,Fib[i-2]);
		strcpy(buf2,Fib[i-1]);
		reverse(buf1,buf1+strlen(buf1));
		reverse(buf2,buf2+strlen(buf2));
		add(buf1,buf2,buf3);
		reverse(buf3,buf3+strlen(buf3));
		strcpy(Fib[i],buf3);
	}
	int n;

	freopen("d:\\UVa\\uva_in.txt", "w", stdout);
	while (scanf("%d", &n) != EOF)
		printf("%s\n", Fib[n]);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值