Fibonacci数列

求高位时

算法分析:f(n)= (1/sqrt(5))*pow((1+sqrt(5))/2,n)- (1/sqrt(5))*pow((1-sqrt(5))/2,n);

这个题目就是用到这个公式,化简f(n)=n*log10((1+sqrt(5))/2)-log10(sqrt(5))+log10(1-((1-sqrt(5))/(1+sqrt(5)))^n)后面红色部分是无穷小量,可以省略。

于是f(n)=n*log10((1+sqrt(5))/2)-log10(sqrt(5))

  1. #include<iostream>  
  2. #include<cstdio>  
  3. #include<cmath>  
  4. using namespace std;  
  5. int a[30];  
  6. int main()  
  7. {  
  8.     int i,n,ans1;  
  9.     double ans,ans2;  
  10.     a[0]=0;a[1]=1;  
  11.     for(i=2;i<21;i++)  
  12.     a[i]=a[i-1]+a[i-2];  
  13.     while(scanf("%d",&n)!=EOF)  
  14.     {  
  15.         if(n<=20)  
  16.         {  
  17.             printf("%d\n",a[n]);  
  18.         }  
  19.         else  
  20.         {  
  21.             ans=n*log10(0.5+0.5*sqrt(5))-log10(sqrt(5));  
  22.             ans1=ans;   //转换成int  
  23.             ans2=ans-ans1;   //求小数位后面的  
  24.             ans=pow(10.0,ans2);  
  25.             ans1=ans*1000;  
  26.             printf("%d\n",ans1);  
  27.         }  
  28.     }  
  29.     return 0;  
  30. }  

用矩阵时:


[cpp]  view plain  copy
  1.    
  2. # include<stdio.h>  
  3. int a[4],b[4],c[4],d[1000000],q;  
  4. void fun(int n)  
  5. {  
  6.         if(n==1)  
  7.         return ;   //到底层是开始返回  
  8.         fun(n/2);  
  9.         b[1]=(a[1]*a[1]+a[2]*a[3])%10000;  
  10.         b[2]=(a[1]*a[2]+a[2]*a[4])%10000;  
  11.         b[3]=(a[3]*a[1]+a[4]*a[3])%10000;  
  12.         b[4]=(a[3]*a[2]+a[4]*a[4])%10000;  
  13.         a[1]=b[1];  
  14.         a[2]=b[2];  
  15.         a[3]=b[3];  
  16.         a[4]=b[4];       
  17.         if(n%2!=0)  
  18.         {  
  19.             b[1]=(a[1]*c[1]+a[2]*c[3])%10000;  
  20.             b[2]=(a[1]*c[2]+a[2]*c[4])%10000;  
  21.             b[3]=(a[3]*c[1]+a[4]*c[3])%10000;  
  22.             b[4]=(a[3]*c[2]+a[4]*c[4])%10000;  
  23.             a[1]=b[1];  
  24.             a[2]=b[2];  
  25.             a[3]=b[3];  
  26.             a[4]=b[4];  
  27.         }  
  28. }  
  29. int main()  
  30. {  
  31.     int n,i;  
  32.     while(scanf("%d",&n))  
  33.     {  
  34.         if(n==-1)  
  35.         break;  
  36.         a[1]=c[1]=0;  
  37.         a[2]=c[2]=1;  
  38.         a[3]=c[3]=1;  
  39.         a[4]=c[4]=1;  
  40.         if(n==0)  
  41.         {  
  42.             printf("0\n");  
  43.             continue;  
  44.         }  
  45.         if(n==1||n==2)  
  46.         {  
  47.             printf("1\n");  
  48.             continue;  
  49.         }  
  50.         i=1;  
  51.         fun(n);  
  52.         printf("%d\n",a[3]);  
  53.     }  
  54.     return 0;  
  55. }          
源博客地址:http://blog.youkuaiyun.com/yuan_lo/article/details/8833086
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值