Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 185042 Accepted Submission(s): 46036
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).
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
问题链接:HDU1005 ZOJ2015 Number Sequence。
问题描述:参见上文。
问题分析:
这是一个有关数列与模除的问题。
斐波拉契数列是人们熟悉的。这个问题的每一项都做了一个算术计算,然后用7进行模除。
根据数论的知识可知,模7的余数值是0-6。若对于正整数k和m,若f(k-2)=f(m-2)且f(k-1)=f(m-1),则f(k)=f(k-2)+f(k-1)=f(m-2)+f(m-1)=f(m),即如果k和m的前两项完全相同,则f(k)=f(m)。这样的数列,若干项之后,其值会循环出现,所以不必将其所有的项都算出来,只需要算出第一个循环的各个项即可。
因此,只需要构建一个长度为n的短数列,各项的值为定义公式计算出来的7的余数,需要知道的是n为多少。如果f(n+1)=1(f(1)=1)且f(n+2)=1(f(2)=1),那么就得到了所要求的n了。
f(n)和f(n+1)的值都是0-6,所以组合有7×7=49种,需要多算2项加上余量,算到52项是够的。
这个问题的测试数据有BUG,没有考虑a和b的取值使得f(n)和f(n+1)都等于0的情况,例如a=b=7。
程序说明:
这个问题的测试数据应该是有BUG。
WA的C语言程序(正解)如下:
/* HDU1005 ZOJ2015 Number Sequence */
#include <stdio.h>
#define N 52
int main(void)
{
int a, b, n;
int t[N + 1];
int i;
t[1] = 1;
t[2] = 1;
while(scanf("%d%d%d", &a, &b, &n) != EOF && (a || b || n)) {
for(i = 3; i <= N; i++) {
t[i] = (a * t[i - 1] + b * t[i - 2]) % 7;
if((t[i] == 1 && t[i - 1] == 1) || (t[i] == 0 && t[i - 1] == 0))
break;
}
if(t[i] == 1 && t[i - 1] == 1) {
t[0] = t[i - 2];
n %= i-2;
printf("%d\n", t[n]);
} else if(t[i] == 0 && t[i - 1] == 0) {
if(n >= i - 1)
printf("%d\n", t[i - 1]);
else
printf("%d\n", t[n]);
}
}
return 0;
}
AC的C语言程序如下:
/* HDU1005 ZOJ2015 Number Sequence */
#include <stdio.h>
#define N 52
int main(void)
{
int a, b, n;
int t[N + 1];
int i;
t[1] = 1;
t[2] = 1;
while(scanf("%d%d%d", &a, &b, &n) != EOF && (a || b || n)) {
for(i = 3; i <= N; i++) {
t[i] = (a * t[i - 1] + b * t[i - 2]) % 7;
if(t[i] == 1 && t[i - 1] == 1)
break;
}
t[0] = t[i - 2];
n %= i - 2;
printf("%d\n", t[n]);
}
return 0;
}
AC的C语言程序(废除)如下:
/* HDU1005 ZOJ2015 Number Sequence */
#include <stdio.h>
int main(void)
{
int a, b;
long n;
int t[102];
int i;
t[1] = 1;
t[2] = 1;
while(scanf("%d%d%ld", &a, &b, &n) != EOF) {
if(a == 0 && b==0 && n==0)
break;
for(i=3; i<102; i++) {
t[i] = (a * t[i-1] + b * t[i-2]) % 7;
if(t[i] == 1 && t[i-1] == 1)
break;
}
t[0] = t[i - 2];
n %= i-2;
printf("%d\n", t[n]);
}
return 0;
}