Fibonacci
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5887 Accepted Submission(s): 2793
Problem Description
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
思路
对于任意一个数可以写成这样的形式
d
.
x
x
x
⋯
∗
1
0
k
−
1
d.xxx\cdots*10^{k-1}
d.xxx⋯∗10k−1
对这个数取对数即得到
l
o
g
10
(
d
.
x
x
x
⋯
)
+
l
o
g
10
(
1
0
k
−
1
)
log_{10}(d.xxx\cdots)+log_{10}(10^{k-1})
log10(d.xxx⋯)+log10(10k−1)
=
k
−
1
+
l
o
g
10
(
d
.
x
x
x
⋯
)
=k-1+log_{10}(d.xxx\cdots)
=k−1+log10(d.xxx⋯)
l
o
g
10
(
d
.
x
x
x
⋯
)
log_{10}(d.xxx\cdots)
log10(d.xxx⋯)为一个
(
0
,
1
)
(0,1)
(0,1)的数字,那么
d
.
x
x
x
⋯
=
1
0
l
o
g
10
(
d
.
x
x
x
⋯
)
d.xxx\cdots=10^{log_{10}(d.xxx\cdots)}
d.xxx⋯=10log10(d.xxx⋯)
然后我们再回来讲这道题,他是要求得斐波那契数列的前4项
我们知道斐波那契数列的通项公式
a
n
=
1
5
(
(
1
+
5
2
)
n
−
(
1
−
5
2
)
n
)
a_{n}=\frac{1}{\sqrt{5}}((\frac{1+\sqrt{5}}{2})^n-(\frac{1-\sqrt{5}}{2})^n)
an=51((21+5)n−(21−5)n)
不知道的话也可以用特征方程求解,
a
n
a_{n}
an的公式还可以转换一下变成
a
n
=
1
5
(
1
+
5
2
)
n
(
1
−
(
1
−
5
1
+
5
)
n
)
a_{n}=\frac{1}{\sqrt{5}}(\frac{1+\sqrt{5}}{2})^n(1-(\frac{1-\sqrt{5}}{1+\sqrt{5}})^n)
an=51(21+5)n(1−(1+51−5)n)
(
1
−
5
1
+
5
)
n
(\frac{1-\sqrt{5}}{1+\sqrt{5}})^n
(1+51−5)n在n大于20的时候就已经非常接近0了,所以这一项可以省去
所以
a
n
=
1
5
(
1
+
5
2
)
n
a_{n}=\frac{1}{\sqrt{5}}(\frac{1+\sqrt{5}}{2})^n
an=51(21+5)n
对其去对数即
l
o
g
10
(
a
n
)
=
l
o
g
10
(
1
5
)
+
n
l
o
g
10
(
1
+
5
2
)
log_{10}(a_{n})=log_{10}(\frac{1}{\sqrt{5}})+nlog_{10}(\frac{1+\sqrt{5}}{2})
log10(an)=log10(51)+nlog10(21+5)
然后我们就可以利用我们一开始介绍的方法来求解
d
.
x
x
x
⋯
d.xxx\cdots
d.xxx⋯
令
x
=
l
o
g
10
(
a
n
)
x=log_{10}(a_{n})
x=log10(an),那么
l
o
g
10
(
d
.
x
x
x
⋯
)
=
x
−
f
l
o
o
r
(
x
)
log_{10}(d.xxx\cdots)=x-floor(x)
log10(d.xxx⋯)=x−floor(x)
d
.
x
x
x
⋯
=
1
0
x
−
f
l
o
o
r
(
x
)
d.xxx\cdots=10^{x-floor(x)}
d.xxx⋯=10x−floor(x),那么前4位就把他乘以1000即可
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cstring>
#include <math.h>
using namespace std;
int main()
{
int f[21];
f[0]=0;
f[1]=1;
for(int i=2;i<21;i++)
f[i]=f[i-1]+f[i-2];
int n;
while(scanf("%d",&n)!=EOF)
{
if(n<=20)
printf("%d\n",f[n]);
else
{
double x=log10(1/sqrt(5))+n*1.0*log10((1.0+sqrt(5))*0.5);
x=x-floor(x);
x=pow(10,x);
x=x*1000;
printf("%d\n",(int)x);
}
}
return 0;
}