大菲波数(高精度)

http://acm.hdu.edu.cn/showproblem.php?pid=1715

问题描述:

Fibonacci数列,定义如下:
f(1)=f(2)=1
f(n)=f(n-1)+f(n-2) n>=3。
计算第n项Fibonacci数值。
 
输入第一行为一个整数N,接下来N行为整数Pi(1<=Pi<=1000)。

问题分析:因为本题要求斐波那契的N的范围是1000,远远超过了长整型的范围。因此必须要考虑到高精度。于是我们可以开辟一个二维数组,用来a[n][i]来保存斐波那契数列。a[n][i]表示第n个斐波那契数的倒数第i个位数表示的数。

而为了节省空间,我们可以先对1000以内的N进行打表。

AC代码:

#include<iostream>
using namespace std;
#include <cmath>
#include <cstring>
#define maxe 1002 
#define N 1005
int a[N][N];
int main(){
	ios::sync_with_stdio(false);
	
	int t,n;
	cin>>t;
	memset(a,0,sizeof(a));
	a[1][1]  = 1;
	a[2][1] = 1;
	int s,plus = 0;
	for(int i = 3;i < N;i++){
		for(int j = 1;j < maxe;j++){
			s = a[i-2][j]+a[i-1][j]+plus;
			a[i][j] = s % 10;
			plus = s / 10;
		}
	}
	
	while(t--){
		int k = maxe;
		cin>>n;
		while(1){
			if(a[n][k])
			break;
			k--;
		}
		for(int i = k;i >= 1;i--){
			cout<<a[n][i];
		}
		cout<<endl;
	}
	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_36711003/article/details/79495404