您的位置:首页 > 其它

杭电_ACM_Hat's Fibonacci

2012-11-05 10:40 232 查看
[align=left]Problem Description[/align]
A Fibonacci sequence is calculated by adding the previous two members the sequence, with the first two members being both 1.
F(1) = 1, F(2) = 1, F(3) = 1,F(4) = 1, F(n>4) = F(n - 1) + F(n-2) + F(n-3) + F(n-4)
Your task is to take a number as input, and print that Fibonacci number.

[align=left]Input[/align]
Each line will contain an integers. Process to end of file.

[align=left]Output[/align]
For each case, output the result in a line.

[align=left]Sample Input[/align]

100


[align=left]Sample Output[/align]

4203968145672990846840663646

Note:
No generated Fibonacci number in excess of 2005 digits will be in the test data, ie. F(20) = 66526 has 5 digits.


View Code

#include <stdio.h>
#include <string.h>
int f[10000][505] = {0};
int main()
{
int n, carry, sum, i, j, length;
//f[number][0] is the length of the number
f[1][0] = 1;
f[1][1] = 1;
f[2][0] = 1;
f[2][1] = 1;
f[3][0] = 1;
f[3][1] = 1;
f[4][0] = 1;
f[4][1] = 1;
while (scanf("%d", &n) != EOF)
{
if (n < 5)
{
puts("1");
continue;
}
for (i = 5; i <= n; i++)
{
f[i][0] = f[i - 1][0];
carry = 0;
//splite the number by four
for (j = 1; j <= f[i][0]; j++)
{
sum = f[i -1][j] + f[i - 2][j] + f[i - 3][j] + f[i - 4][j] + carry;
f[i][j] = sum % 10000;
carry = sum / 10000;
}
//if the carry is not zero, then the length must plus one
if (carry != 0)
{
f[i][0]++;
f[i][j] = carry;
}
}
//formatted printing
length = f
[0];
printf("%d", f
[length]);
for (i = length - 1; i >= 1; i--)
printf("%04d",f
[i]);
printf("\n");
}
return 0;
}


Main points

firstly, you can't use string in C and if the array is big, you must declare in global variable.

secondly, the question is splitting the number by four, or you will accure Runtime Error (ACCESS_VIOLATION). The one diffence with spliting by one is you should use %d firstly, then use %04d.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: