HDU1568 Fibonacci 斐波那契的前4位

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1568



分析:对于一个数来说,求前4为无非就是我们把这个数表示成d.xxxx的形式,然后取整即可,我们设该数为s,那么有:

s=d.xxx*10^(len-4)

log10(s)=log10(d.xxxxx)+log10(10^(len-4))=log10(d.xxxx)+len-4;

log10(s)+4-len=log10(d.xxxx)

d.xxxx=10^(log10(s)+4-len)

s=(1/sqrt(5))*[(1+sqrt(5))/2.0]^i;

len=(int)log10(s)+1;

d.xxxx=10^(log10(s)+4-((int)log10(s)+1))=10^(log10(s)-(int)log10(s)+3);

然后对d.xxxx取整,即为所求。


实现代码如下:

#include <cstdio>
#include <math.h>
using namespace std;
const int MAX=100000001;
int f[MAX];
int main()
{
    int n,i;
    f[0]=0;f[1]=1;
    for(i=2;i<=20;i++)
      f[i]=f[i-1]+f[i-2];
    while(scanf("%d",&n)!=-1)
    {
        if(n<=20)
          printf("%d\n",f[n]);
        else
        {
            int len=0;
            double s=0,temp=0;
            temp=-0.5*log10(5.0)+n*(log10((1+sqrt(5.0))/2));
            len=(int)temp+1;
            s=pow(10.0,temp-len+4);
            printf("%d\n",(int)s);
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值