Problem Description
2007年到来了。经过2006年一年的修炼,数学神童zouyu终于把0到100000000的Fibonacci数列
(f[0]=0,f[1]=1;f[i] = f[i-1]+f[i-2](i>=2))的值全部给背了下来。 接下来,CodeStar决定要考考他,于是每问他一个数字,他就要把答案说出来,不过有的数字太长了。所以规定超过4位的只要说出前4位就可以了,可是CodeStar自己又记不住。于是他决定编写一个程序来测验zouyu说的是否正确。 |
Input
输入若干数字n(0 <= n <= 100000000),每个数字一行。读到文件尾。
|
Output
输出f[n]的前4个数字(若不足4个数字,就全部输出)。 |
Sample Input
0 1 2 3 4 5 35 36 37 38 39 40 |
Sample Output
0 1 1 2 3 5 9227 1493 2415 3908 6324 1023 |
View Code
1 #include <stdio.h> 2 #include <math.h> 3 short a[21] = {0, 1, 1}; 4 int main() 5 { 6 int i, n; 7 double temp, result; 8 //handle those number n <= 20 9 for(i = 2; i <= 20; i++) 10 { 11 a[i] = a[i - 1] + a[i - 2]; 12 } 13 while (scanf("%d", &n) != EOF) 14 { 15 //if n <= 20 then get it straightly 16 if (n <= 20) 17 { 18 printf("%d\n", a[n]); 19 continue; 20 } 21 //if n > 20, use the regular 22 temp = n * log((1.0 + sqrt(5.0)) / 2.0) / log(10.0) - 0.5 * log(5.0) / log(10.0); 23 result = pow(10.0, temp - floor(temp)); 24 //handle the result 25 while (result < 1000) 26 result *= 10; 27 printf("%d\n", (int)result); 28 } 29 return 0; 30 }
pay attention
firstly, using the regular to get the Fibonacci number, which you can find in the internet.
secondly, because the above regular just depend on n, so you need not get all results,then input, what you must do is just according the input, then get the result only !
thirdly, for scanf, you must use != EOF, if you use cin, you need not use it.
forthly, log10((double)n) = log((double)n) / log(10);
last but not the least, the question use log10() to handle the big number. crucial!!