1. 程式人生 > >斐波那契數列 遞迴超時問題

斐波那契數列 遞迴超時問題

斐波那契數列

在進行演算法運算時,使用遞迴運算,運算速度較慢。根據要求用陣列儲存比較快。

這次的題目中,是直接計算其餘數。

題目:

Fibonacci數列的遞推公式為:Fn=Fn-1+Fn-2,其中F1=F2=1。

當n比較大時,Fn也非常大,現在我們想知道,Fn除以10007的餘數是多少。

  1. #include<stdio.h>  
  2. #define M 10007  
  3. int main()    
  4. {    
  5.     int a1,a2;    
  6.     a1=a2=1;    
  7.     int temp;  
  8.     long n;    
  9.     long i;    
  10.     scanf("%ld"
    ,&n);    
  11.     for(i=1;i<n;i++)    
  12.     {     
  13.         temp=a2;    
  14.         a2=(a1+a2)%M;    
  15.         a1=temp;     
  16.     }   
  17.     printf("%d\n",a1);    
  18.     return 0;    
  19. }