Fibonacci
Description
2007年到来了。经过2006年一年的修炼,数学神童zouyu终于把0到100000000的Fibonacci数列
(f[0]=0,f[1]=1;f[i] = f[i-1]+f=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
题解:
题是个挺有意思的题 以前在lijhtoj上写过一个思想非常类似的 见下图 不过还是在学长给出通项公式的基础下才写出来的TAT
(本来遇到这个题是在某个小oj上卡精度卡的恶心
//这里是前4位
AC代码
#include <bits/stdc++.h>
using namespace std;
int arr[40];
void init()
{
arr[1] = 1, arr[2] = 1;
for(int i = 3; i <= 40; i++) {
arr[i] = arr[i-1] +arr[i-2];
if(arr[i] > 9999) break;
}
}
int main()
{
init();
int n;
while(~scanf("%d",&n)) {
if(n <= 20) {
printf("%d\n",arr[n]); continue;
}
double zz = -0.5*log10(5.0) + 1.0*n*log10((1+sqrt(5.0))/2.0);
double yy = pow(10.0,zz-(int)zz);
printf("%d\n",(int)(yy*1000));
}
return 0;
}