斐波那契數列 遞迴超時問題
阿新 • • 發佈:2019-01-07
斐波那契數列
在進行演算法運算時,使用遞迴運算,運算速度較慢。根據要求用陣列儲存比較快。
這次的題目中,是直接計算其餘數。
題目:
Fibonacci數列的遞推公式為:Fn=Fn-1+Fn-2,其中F1=F2=1。
當n比較大時,Fn也非常大,現在我們想知道,Fn除以10007的餘數是多少。
- #include<stdio.h>
- #define M 10007
- int main()
- {
- int a1,a2;
- a1=a2=1;
- int temp;
- long n;
- long i;
-
scanf("%ld"
- for(i=1;i<n;i++)
- {
- temp=a2;
- a2=(a1+a2)%M;
- a1=temp;
- }
- printf("%d\n",a1);
- return 0;
- }