斐波那契数列 通项公式 [数学]

    xiaoxiao2021-03-26  11

    [2007年到来了。经过2006年一年的修炼,数学神童zouyu终于把0到100000000的Fibonacci数列 (f[0]=0,f[1]=1;f[i] = f[i-1]+f=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

    题解

    先求出其通项公式如下

    Fn=15(1+52)n(152)n

    证明过程

    有了公式后还要注意一点就是它只要输出前4位,方法链接

    lgFn=lg5+lg(1+52)n(152)n=lg5+lg(1+52)n+lg1(151+5)nlg5+nlg(1+52)

    那么它前四位就是 [10{lgFn}+3] (注:{}为取小数部分,[]为取整数部分)

    代码如下

    #include<stdio.h> #include<math.h> #include<algorithm> using namespace std; const double sqrt_5=sqrt(5.0); const double a=sqrt_5/5; const double b=(1+sqrt_5)/2; const double c=(1-sqrt_5)/2; int fib1(int n){ int fn=a*(pow(b,n)-pow(c,n)); return fn; } int fib2(int n){ double fn=log10(a)+log10(b)*n; fn=fn-floor(fn); fn=pow(10.0,fn); fn=floor(1000*fn); return (int)fn; } int main() { int n; while(scanf("%d",&n)!=EOF){ if(n<21) printf("%d\n",fib1(n)); else printf("%d\n",fib2(n)); } return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-600249.html

    最新回复(0)