Fibonacci
2007年到来了。经过2006年一年的修炼,数学神童zouyu终于把0到100000000的Fibonacci数列
(f[0]=0,f[1]=1;f[i] = f[i-1]+fi-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
题解
看到这个范围我就给跪了。自己的数论知识小水坑里面找不到丝毫用得上的东西。
斐波拉契数列不仅仅有递推公式
F
(
n
)
=
F
(
n
−
1
)
+
F
(
n
−
2
)
F(n)=F(n-1)+F(n-2)
F(n)=F(n−1)+F(n−2)
还有通项公式
F
n
=
1
5
[
(
1
+
5
2
)
n
−
(
1
−
5
2
)
n
]
F_n=\cfrac{1}{\sqrt{5}}\big[(\frac{1+\sqrt{5}}{2})^n-(\frac{1-\sqrt{5}}{2})^n\big]
Fn=51[(21+5)n−(21−5)n]
l
o
g
10
F
(
n
)
=
l
o
g
10
1
5
(
1
+
5
2
)
n
[
1
−
(
1
−
5
1
+
5
)
n
]
≈
l
o
g
10
1
5
+
n
l
o
g
10
1
+
5
2
log_{10}{F(n)}=log_{10}\cfrac{1}{\sqrt{5}}(\cfrac{1+\sqrt{5}}{2})^n\big[1-(\cfrac{1-\sqrt{5}}{1+\sqrt{5}})^n\big]\approx\ log_{10}{\cfrac{1}{\sqrt{5}}}+nlog_{10}{\cfrac{1+\sqrt{5}}{2}}
log10F(n)=log1051(21+5)n[1−(1+51−5)n]≈ log1051+nlog1021+5
因为前二十个数本身就是小于等于四位数的,所以前面20个打表
代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <cmath>
using namespace std;
#define me(x,y) memset(x,y,sizeof x)
#define MIN(x,y) x < y ? x : y
#define MAX(x,y) x > y ? x : y
typedef long long ll;
const int maxn = 1e7;
const double INF = 0x3f3f3f3f;
const int MOD = 10007;
int main(){
int n;
int fib[22];
fib[1]=1,fib[2]=1;
for(int i = 3; i <= 20; ++i) fib[i] = fib[i-1]+fib[i-2];
while(cin>>n){
if(n == 0){
cout<<0<<endl;
continue;
}
if(n <= 20){
cout<<fib[n]<<endl;
continue;
}
double a = 1/sqrt(5),b=(1+sqrt(5))/2;
double k = log10(a)+n*log10(b);
k = k-floor(k);
double ans = pow(10,k);
cout<<(int)(ans*1000)<<endl;
}
return 0;
}
/*
*/