/*最fibonacci的定义*/
#include<iostream>
using namespace std;
int main()
{
__int64 f[10000],n;
f[0]=0;f[1]=1;f[2]=1;
while(scanf("%I64d",&n)!=EOF)
{
for(__int64 i=2;i<=n;i++)
f[i]=f[i-1]+f[i-2];
printf("%I64d\n",f[n]);
}
return 0;
}
/*用矩阵相乘实现fibonacci(本题是求f(n)最后四位数)*/
#include<iostream>
#include<stack>
using namespace std;
const __int64 size = 2;
const __int64 mod = 10000;
struct Matrix{
__int64 a[size][size];
Matrix operator*(const Matrix &B)
{
Matrix t;
__int64 i,j,k;
for(i=0;i<size;i++)
for(j=0;j<size;j++)
{
t.a[i][j]=0;
for(k=0;k<size;k++)
{
t.a[i][j]+=a[i][k]*B.a[k][j];
t.a[i][j]%=mod;
}
}
return t;
}
Matrix pow(__int64 n)
{
if(n==0)
{
Matrix t;
memset(t.a,0,sizeof(t.a));
for(__int64 i=0;i<size;i++)
t.a[i][i]=1;
return t;
}
if(n==1)
return *this;
else
{
Matrix temp=(*this)*(*this);
if(n&1)
return temp.pow(n>>1)*(*this);
else
return temp.pow(n>>1);
}
}
}M;
int main()
{
__int64 n;
M.a[0][0]=0;M.a[0][1]=1;M.a[1][0]=1;M.a[1][1]=1;
while(scanf("%I64d",&n)!=EOF&&n!=-1)
{
Matrix t=M.pow(n);
printf("%d\n",t.a[0][1]);
}
return 0;
}
Fibonacci
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2206 Accepted Submission(s): 1032
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
Author
daringQQ
Source
Happy 2007
Recommend
8600
/*f(n)=1/sqrt(5)(((1+sqrt(5))/2)^n+((1-sqrt(5))/2)^n)
假设F[n]可以表示成 t * 10^k(t是一个小数),那么对于F[n]取对数log10,答案就为log10 t + K,
此时很明显log10 t<1,于是我们去除整数部分,就得到了log10 t ,再用pow(10,log10 t)我们就还原回了t。将t×1000就得到了F[n]的前四位。
具体实现的时候Log10 F[n]约等于((1+sqrt(5))/2)^n/sqrt(5),这里我们把((1-sqrt(5))/2)^n这一项忽略了,
因为当N>=40时,这个数已经小的可以忽略。于是log10 F[n]就可以化简成log10 1/sqrt(5) + n*log10 (1+sqrt(5))/2
*/
/*算法分析:f(n)= (1/sqrt(5))*pow((1+sqrt(5))/2,n) - (1/sqrt(5))*pow((1-sqrt(5))/2,n);
这个题目就是用到这个公式,化简f(n)=n*log10((1+sqrt(5))/2)-log10(sqrt(5))+log10(1-((1-sqrt(5))/(1+sqrt(5)))^n)后面红色部分是无穷小量,可以省略。
于是f(n)=n*log10((1+sqrt(5))/2)-log10(sqrt(5));*/
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int a[21];int main()
{
int i,n,ans1;
double ans,ans2;
a[0]=0;a[1]=1;
for(i=2;i<=20;i++) a[i]=a[i-1]+a[i-2];
while(scanf("%d",&n)!=EOF)
{
if(n<=20)
{
printf("%d\n",a[n]);
}
else
{
ans=n*log10(0.5+0.5*sqrt(5))-log10(sqrt(5));
ans1=ans;
ans2=ans-ans1;
ans=pow(10.0,ans2);
ans1=ans*1000;
printf("%d\n",ans1);
}
} return 0;
}