题目链接: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;
}