http://acm.hdu.edu.cn/showproblem.php?pid=1568

来源:互联网 发布:北大青鸟java课程表 编辑:程序博客网 时间:2024/06/07 12:11

这道题太精辟了,一开始刚见到这道题木有一点思路,,,最后看看了别人的解题思路,,首先先用fibonacci公式求出其值,然后运用对数的性质,,去整取零,,,因为影响结果的只是小数部分,,,然后用小数部分一直乘10直到大于1000时停下,,,,

斐波纳契的计算公式:(1/√5) * [((1+√5)/2)^n-((1-√5)/2)^n](n=1,2,3.....)

log10((1/√5) * [((1+√5)/2)^n-((1-√5)/2)^n])

化简一下得到:

-0.5*log10(5.0)+((double)n)*log(f)/log(10.0)+log10(1-((1-√5)/(1+√5))^n)其中f=(sqrt(5.0)+1.0)/2.0;

在这里 log10(1-((1-√5)/(1+√5))^n)无穷小可以忽略不计!

最后得到 log10(an)=-0.5*log10(5.0)+((double)n)*log(f)/log(10.0)!

代码:

#include<iostream>#include<cstdio>#include<cmath>using namespace std;int s[21]={0,1,1,2};const double f=((double)sqrt(5)+1)/2.0;void get_Fibonacci(int x){    if(x<=20)        printf("%d\n",s[x]);    else{                 double ans=(-0.5)*log(5.0)/log(10.0)+(double(x))*log(f)/log(10.0);        ans=ans-floor(ans);        double k=pow(10.0,ans);        while(k<1000.0)            k*=10.0;        printf("%d\n",(int)k);    }     }int main(){    int x,i;    for(i=3;i<=20;i++)        s[i]=s[i-1]+s[i-2];    while(~scanf("%d",&x)){        if(x==0){            printf("0\n");            continue;           }        get_Fibonacci(x);    }    return 0;}

法二:

#include<cmath>#include<iostream>const double f=(sqrt((double)5)+1)/2;using namespace std;int get(int x){double k=-0.5*log10((double)5)+x*log10(f);    k=k-(int)k;k=pow(10.0,k);while(k<1000)k*=10;return (int)k;}int main(){int a[21];a[0]=0,a[1]=a[2]=1;for(int i=2;i<=21;++i)a[i]=a[i-1]+a[i-2];  int n;  while(cin>>n)  {  if(n<=20) {cout<<a[n]<<endl;continue;}  else  {  cout<<get(n)<<endl;  }  }return 0;}

求后几位的话,可以构造矩阵相乘,二分求冪

求前几位,不需要,直接运用数学公式和对数的性质来求

斐波那契数列通项公式

an=(1/√5)* [((1+√5)/2)^n-((1-√5)/2)^n]

求x^y的前几位
高斯函数x=[x]+{x},[x]为x的整数部分,{x}为x的小数部分
运用对数性质,t=x^y=a*10^n(科学计数法)
lgt=y*lgx=lga+n (n=[lgt],lga={lgt},因为1<=a<10,所以0<=lga<1)
a=10^{lgt}
e=y*lgx, e=e-[e], a=10^e






原创粉丝点击