hdu 1568 Fibonacci

简介:

点击此处即可传送hdu 1568

                               **Fibonacci**


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

解题思路:直接给出公式:

y=log10(1/sqrt(5))+m*log10(((1+sqrt(5))/2)+4-(int)(log10(1/sqrt(5))+m*log10(((1+sqrt(5))/2)+1)
ans = pow(10.0, y);
详细推导过程:
比如说:123456的前4位,123456 = 1234.56*10^(6-4);
两边取对数:
log(10)123456 = 2 +log(1234.56)
1234.56 = 10^(log(10)123456 - 2)
两边取整就行了
6就是总位数,4是输出几位数;
然后根据斐波那契数列的封闭公式
F(n) = 1.0/sqrt(5) *((1+sqrt(5))/2.0)^n-(1-sqrt(5))/2.0)^n)
当然(1+sqrt(5))/2.0)^n这个数当n很大时可以舍去;
所以 F(n)~ 1.0/sqrt(5) *(1+sqrt(5))/2.0)^n
总位数:log10(1/sqrt(5))+m*log10(((1+sqrt(5))/2)

上代码:

/*
2015 - 8 - 13
Author: ITAK
今日的我要超越昨日的我,明日的我要胜过今日的我,
以创作出更好的代码为目标,不断地超越自己。
*/
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int data[30];
int main()
{
    data[0] = 0;
    data[1] = 1;
    for(int i=2; i<=20; i++)
        data[i] = data[i-1]+data[i-2];
    int m;
    //判断多少位开始大于10000
    //for(int i=0; i<=20; i++)
      //  cout<<data[i]<<endl;
    while(~scanf("%d",&m))
    {
        if(m < 21)
        cout<<data[m]<<endl;
        else
        {
            double y = log10(1.0/sqrt(5))+m*log10((1.0+sqrt(5))/2.0)+4
                       -(int)(log10(1.0/sqrt(5))+m*log10((1.0+sqrt(5))/2.0)+1);//注意取整
            int ans = (int)pow(10.0,y);
            cout<<ans<<endl;
        }
    }
    return 0;
}
目录
相关文章
|
算法
|
机器学习/深度学习
POJ 1775 (ZOJ 2358) Sum of Factorials
POJ 1775 (ZOJ 2358) Sum of Factorials
122 0
|
Java
HDU 1021 Fibonacci Again
Fibonacci Again Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 58267    Accepted Submission(...
889 0
|
机器学习/深度学习 Java
|
人工智能 机器学习/深度学习
POJ 1775 (ZOJ 2358) Sum of Factorials
Description John von Neumann, b. Dec. 28, 1903, d. Feb. 8, 1957, was a Hungarian-American mathematician who made important contributions t...
1113 0