以前没有发现,斐波那契通项公式能直接KO一题。记录一下,许多的过程细节值得回味。
nyist 461 Fibonacci数列(四)
大意:求出斐波那契f[n]的前4个数字
因为不是后几位所以不能矩阵快速幂。
利用通项公式:
趋近于0,于是转换成
以便我们使用对数,解决数字太大的问题。
关于误差:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const double f=sqrt(5.0);
int main()
{
int n;
while(cin>>n){
double p1=pow((1+f)/2,n);
double p2=pow((1-f)/2,n);
double ans=(p1-p2)/f;
printf("%-4.0lf\n",ans);
}
return 0;
}
/*
但是发现它会超过double的极限
900
54877108839481660000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000
1000
43466557686938915000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000
10000
1
*/
同时发现,大数
后面有很多的0!
在N很大的时候,
关于误差:
double f=sqrt(5);
double a=(1-f)/2;
for(int i=15;i<25;i++){
cout<<pow(a,i)<<endl;
}
-0.000733137
0.000453104
-0.000280034
0.00017307
-0.000106963
6.6107e-005
-4.08563e-005
2.52506e-005
-1.56057e-005
9.64488e-006
--------------------------------
Process exited with return value 0
Press any key to continue . . .
于是:
设p=logx,那么P的整数部分就成就大数后面很多的0,它的小数部分成就了大数前面的非0数字
最后处理一下即可
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const double f=sqrt(5.0);
int main()
{
int n;
while(cin>>n){
if(n<25){
double p1=pow((1+f)/2,n);
double p2=pow((1-f)/2,n);
double ans=(p1-p2)/f;
int res=int(ans);
while(res>=10000){
res/=10;
}
printf("%d\n",res);
}
else {
double p=log(1/f)/log(10.0)+log((1+f)/2)/log(10.0)*n;
p=p-floor(p); // floor 向下取整
double ans=pow(10,p);
while(ans<1000){
ans=ans*10;
}
printf("%d\n",int(ans));
}
}
return 0;
}