Fibonacci
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4892 Accepted Submission(s): 2272
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说的是否正确。
(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
看完题解才知道是数学题,心累。
这题要用到对数的性质
比如n = 12345678,log10(12345678)= log10(1.2345678*10^7) = log10(1.2345678)+7
log10(1.2345678)即是log10(12345678)的小数部分
log10(1.2345678) = 0.091515
10^0.091515 = 1.2345678
所以求出斐波那契递推式f(n),再求log10(f(n))取小数部分x,再求10^x取前四位有效数字,即可求得斐波那契数前四位
斐波那契公式 f(n) = (1/sqrt(5)) * [((1+sqrt (5))/2)^n-((1-sqrt(5))/2)^n] (n=1,2,3.....)
![](http://acm.hdu.edu.cn/forum/attachment/9_17558_66eb0d62d0d7087.jpg)
取完对数
![](http://acm.hdu.edu.cn/forum/attachment/9_17558_9a6217715ff7acd.jpg)
因为log10(1-((1-sqrt(5)) / (1+sqrt(5))) ^ n) 趋近0,由上述对数性质可知,省去对前四位影响不大
最终
log(f(n)) = -0.5 * log(5.0) / log(10.0) + 1.0*n * log((sqrt(5.0)+1) / 2) / log(10.0);
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<vector>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define CL(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
const int maxn = 1e8+10;
const int MOD = 1e9+7;
int cnt[22] = {0, 1, 1};
int main(){
int a, b, n, kcase = 1;
for(int i = 3; i <= 20; i++) cnt[i] = cnt[i-1] + cnt[i-2];
while(scanf("%d", &n) == 1){
if(n <= 20){
printf("%d\n", cnt[n]);
continue;
}
double ans = -0.5 * log(5.0) / log(10.0) + 1.0*n * log((sqrt(5.0)+1) / 2) / log(10.0);
ans -= floor(ans);//floor取不大于ans的最大整数
ans = pow(10.0, ans);
while(ans < 1000) ans *= 10;
printf("%d\n", (int)ans);
}
return 0;
}