Fibonacci(数学)

xiaoxiao2021-02-27  213

点击打开链接 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

以上两个公式是此题的关键,另外一个地方就是求出了  log10( f (n) ) 从而求 f ( n ) 的方法。

 

取首位数代码:

#include<stdio.h> #include<math.h> int main() { double x,tmp; while(scanf("%lf",&x)!=EOF) { tmp=log(x)/log(10.0); tmp=tmp-floor(tmp); tmp=pow(10.0,tmp); printf("%d\n",(int)tmp+0.000001); //控制精度否则输入个位数会出现问题 } return 0; } 2.

#include <stdio.h> #include <math.h> int main() { int ans; double num,a; double x; scanf("%lf",&num); x=log10(num); a=pow(10.0,x-(__int64)x); ans=int(a); printf("%d\n",ans); return 0; }

这是百度百科找来的说明,要掌握对数的运算性质。

完了算出小数部分,乘1000就是前4位了。

代码如下:

[cpp]  view plain  copy  print ? #include <cstdio>   #include <cmath>   int main()   {       int f[22]={0,1,1};       for (int i = 3 ; i <= 20 ; i++)           f[i] = f[i-1] + f[i-2];       double n;       double a1 = log10(1.0 / sqrt(5));       double a2 = log10((1 + sqrt(5)) / 2);       while (~scanf ("%lf",&n))       {           if (n <= 20)           {               printf ("%d\n",f[(int)n]);               continue;           }           double ans = a1 + n * a2;           ans -= floor(ans);           ans = pow (10,ans);           ans = (int)(ans * 1000);           printf ("%.lf\n",ans);       }       return 0;   }  
转载请注明原文地址: https://www.6miu.com/read-11469.html

最新回复(0)