【HDU】-1568-Fibonacci(公式+log取小数)

Fibonacci

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4913    Accepted Submission(s): 2292


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

题解:这道题首先要知道公式: an= (1/√5) * [((1+√5)/2)^n - ((1-√5)/2)^n] (n=1,2,3.....),公式两边对10求导。



log10(an)=-0.5*log10(5.0)+((double)n)*log((sqrt(5.0)+1.0)/2.0)/log(10.0)+log10(1-((1-√5)/(1+√5))^n)
log10(1-((1-√5)/(1+√5))^n)--->0
所以写成log10(an)=-0.5*log10(5.0)+((double)n)*log(f)/log(10.0);

最后就是通过与1000比较求出4位数的操作了;

#include<iostream>  
#include<cstdio>  
#include<cmath>  
#include<algorithm>  
using namespace std;  
int f[21]={0,1,1};  
int main()  
{  
    int n;  
    for(int i=2;i<21;i++)  
        f[i]=f[i-1]+f[i-2];  
    while(scanf("%d",&n)!=EOF)  
    {  
        if(n<=20)  
        {  
            printf("%d\n",f[n]);  		//开始较小直接输出 
            continue;  
        }  
        else  
        {  
            double t= -0.5*log(5.0)/log(10.0)+((double)n)*log((sqrt(5.0)+1.0)/2.0)/log(10.0);  
            t-=floor(t);  		//向下取整,保证 t-floor(t)>0 
            t=pow(10.0,t);  
            while(t<1000)  
                t*=10;  
            printf("%d\n",(int)t);  
        }  
    }  
    return 0;  
} 




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值