以前没有发现,斐波那契通项公式能直接KO一题。记录一下,许多的过程细节值得回味。
nyist 461 Fibonacci数列(四)
#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 */
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 . . .
#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; }