题目:
A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
分析:
直接递归会Memory Limit Exceeded
找规律,可以发现最后结果是mod7,而且只与f(n-1)和f(n-2)有关,可以得出有循环规律,至少49个元素就会重复一次,所以只记录前49次结果,之后的值mod49得到。
代码:
#include <iostream>
#include<string.h>
using namespace std;
int main() {
int a, b, n;
while (cin>>a>>b>>n) {
if (a==0&&b==0&&n==0)
break;
int f[49];
memset(f, 0, 49);
f[1]=f[0]=1;
for (int i=2; i<49; i++)
f[i]=(a*f[i-1]+b*f[i-2])%7;
cout<<f[(n-1)%49]<<endl;
}
return 0;
}