用什么方法才能不超时?不求和要怎样直接求余数?

问题描述:

图片说明图片说明

/*Fibonacci数列的递推公式为:Fn=Fn-1+Fn-2,其中F1=F2=1。
当n比较大时,Fn也非常大,现在我们想知道,Fn除以10007的余数是多少。*/
#include <iostream>
#include <cmath>
#define M 10007
using namespace std;
int fun(int n)
{
    if (n == 1 || n == 2)
        return 1;
    else
        return fun(n - 1) + fun(n - 2);
}
int main()
{
    int n;
    cin >> n;
    cout << fun(n)%M << endl;
    return 0;
}

int fun(int n)
{
if (n == 1 || n == 2)
return 1;
else
return fun(n - 1) + fun(n - 2);
}
这个方法最慢
可以用
int fun(int n)
{
int a = 1;
int b = 1;
for (int i = 1; i < n; i++)
{
b = a + b;
a = b - a;
}
return b % 10007;
}