题目来自杭电ACM: acm.hdu.edu.cn
Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 134355 Accepted Submission(s): 32628
Problem Description
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).
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).
Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
Output
For each test case, print the value of f(n) on a single line.
Sample Input
1 1 3 1 2 10 0 0 0
Sample Output
2 5
Author
CHEN, Shunbao
Source
又是一个和斐波那契数列一样的式子,明显不能使用递归的方法,于是就先使用迭代写了代码如下:
#include <stdio.h>
#define N 100000010
int f[N];
int main()
{
f[1] = 1;
f[2] = 1;
int a, b, n, i;
scanf("%d%d%d", &a, &b, &n);
if (n == 0 && a == 0 && b == 0) {
}
else {
for (i = 3; i <= n; ++i) {
f[i] = (a * f[i-1] + b * f[i-2]) % 7;
}
printf("%d", f[n]);
}
return 0;
}
提交后是:Memory Limit Exceeded,内存超出,因此也不能使用迭代的方法。那么此时要么从给出的递归公式推出相应的通项公式,要么从其中寻找一定的规律。因为A,B是不确定值,所以求通项肯定很困难,同时,我们可以看到在公式中有取余的存在,因此数列肯定是循环数列,又因为取7的余数,则数列的每一项一定不大于7,那么最大有7x7=49中可能,于是我们便可以把数组的大小减小到60,在前60个数中找到循环位置,那么便可以轻松求解。
改进后代码如下:
#include <stdio.h>
int f[60];
int main()
{
int a, b, n, i, j;
while (scanf("%d%d%d", &a, &b, &n) != EOF) {
int beg = 1, end = 1;
f[0] = f[1] = f[2] = 1;
if (n == 0 && a == 0 & b == 0) {
break;
}
for (i = 3; i < 60; ++i) {
f[i] = (a*f[i-1] + b*f[i-2]) % 7;
for (j = end+2; j < i; ++j) {
if (f[i] == f[j] && f[i-1] == f[j-1]) {
beg = j - 2;
end = i - 2;
break;
}
}
}
f[0] = f[end-1];
f[1] = f[end];
if (n == 1 || n == 2) {
printf("%d\n", 1);
}
else{
printf("%d\n", f[n%(end-beg)]);
}
}
return 0;
}
开始一直wa,后来发现没有在输入一次数据后没有对f[1],f[2]初始化,导致下次输出的结果有误,把数组的初始化放入while循环中就可以ac了。