题意求斐波那契数列的第n项。
longlong装不下。
代码:
#include <stdio.h>
int a[1005][220];
void Fibonacci()
{
a[1][0] = 1;
a[1][1] = 1;
a[2][0] = 1;
a[2][1] = 1;
int len = 1;
for (int i = 3; i < 1005; i++)
{
int yu = 0;
for (int j = 1; j <= len; j++)
{
int t = a[i - 1][j] + a[i - 2][j] + yu;
a[i][j] = t % 10;
yu = t / 10;
}
while(yu)
{
a[i][++len] = yu % 10;
yu /= 10;
}
a[i][0] = len;
}
}
int main()
{
Fibonacci();
int ncase;
scanf("%d", &ncase);
while (ncase--)
{
int n;
scanf("%d", &n);
//printf("------%d\n", a[n][0]);
for (int i = a[n][0]; i > 0; i--)//a[n][0] 为数字的长度
printf("%d", a[n][i]);
printf("\n");
}
return 0;
}
另一种写法:
#include<iostream>
using namespace std;
const int N = 1007;
int f[N][217];
int main()
{
int i, j;
f[1][0] = f[2][0] = 1;
for(i = 3; i < N; i++)
{
for(j = 0; j <= 210; j++)
f[i][j] = f[i-1][j]+f[i-2][j];
int flag = 0;
for(j = 0; j <= 210; j++)
{
int tmp = f[i][j] + flag;
flag = tmp/10;
f[i][j] = tmp%10;
}
}
//freopen("data.in", "r", stdin);
int n, pi;
cin >> n;
while(n--)
{
cin >> pi;
i = 210;
while(f[pi][i] == 0)
i--;
cout<<"--------"<<i<<endl;
for(; i >= 0; i--)
cout<<f[pi][i];
cout<<endl;
}
return 0;
}