HDOJ---1568 Fibonacci[公式求前四位数]

 

Fibonacci

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


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
 

 

Author
daringQQ
 

 

Source
 

 

Recommend
8600
 
 
 
 
 

标准的Fibonacci数列F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n - 2)。通项公式为F(n) = (((1+Sqrt(5))/2)^n - ((1-Sqrt(5))/2)^n)*1/Sqrt(5),因为(1-sqrt(5))/2的绝对值小于1,所以当i较大的时候,往往可以忽略掉这一项F(n)≈((1+Sqrt(5))/2)^n/sqrt(5)。所以Fibonacci前30项可直接求出。后面的大数取log10,取整后求出左边4位,方法和HDOJ1060类似http://hi.baidu.com/racebug/blog/item/e3b5cdefeb485af2b2fb9537.html

这个是对Fibonacci介绍很全的一个论文http://blog.163.com/baobao_zhang@126/blog/static/482523672008826103832368/

code :
 1 #include<iostream>

 2 #include<cmath>

 3 using namespace std;

 4 int main()

 5 {

 6     int n;

 7     int i;

 8     int f[31];

 9     double temp1=log10((1.0+sqrt(5.0))/2.0),temp2=log10(sqrt(5.0));

10     f[0]=0;

11     f[1]=1;

12     for(i=2;i<31;i++)

13         f[i]=f[i-1]+f[i-2];

14     while(~scanf("%d",&n))

15     {

16         if(n<31)

17         {

18             int temp=f[n];

19             while(temp>=10000)

20                 temp/=10;

21             printf("%d\n",temp);

22         }

23         else

24         {

25             double t;

26             int ans;

27             t=(n*temp1-temp2);

28             t-=(int)t;

29             ans=pow(10.0,t)*1000.0;

30             printf("%d\n",ans);

31         }

32     }

33     return 0;

34 }

你可能感兴趣的:(fibonacci)