NumberSequence
Time Limit: 2000/1000 MS(Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 179424 Accepted Submission(s):44605
Problem Description
A number sequenceis 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 consistsof multiple test cases. Each test case contains 3 integers A, B and n on asingle line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zerossignal the end of input and this test case is not to be processed.
Output
For each testcase, 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
一道数学题,题意叶特别简单,就是给定了A,B的值就确定了一个函数,进而决定了一个序列里面的数值,数值存在数组中
面对一般带求模运算的表达式,其最终的结果一般都是周期性的,解决这类题目的首要前提便是取寻找周期值
先贴AC代码
#include<stdio.h>
intmain()
{
int i,n,A,B;
int f[62];
while(scanf("%d%d%d",&A,&B,&n)!=EOF)
{
if (A + B + n == 0) break;
f[1]=f[2]=1;
for(i=3;i<62; i++)
{
f[i] = (A * f[i-1] + B *f[i-2]) % 7;
if((f[i] == f[2])&& (f[i-1] == f[1]) )//判断是否出现周期
break;
}
i-=2;
if (n%i == 0)
n = i;
else
n %= i;
printf("%d\n", f[n]);
}
return 0;
}
在这里面,这段话尤其重要,
for(i=3;i<62; i++)
{
f[i] = (A* f[i-1] + B * f[i-2]) % 7;
if((f[i]== f[2]) && (f[i-1] == f[1]) )//判断是否出现周期
break;
}
if((f[i] == f[2]) && (f[i-1] ==f[1]) ) break;
/判断是否出现周期,这里这样做很冒险,单纯凭两个数值满足要求便确定了周期,不严谨,但是有效,结果也能够AC,对于这种可以多次上传代码的题目,不严谨可以通过多次实验进行改进。
其实还有一个方法就是目测,目测叶可以通过相应代码实现,如下
#include<stdio.h>
intmain()
{
int i,n,A,B;
int f[62];
while(scanf("%d%d%d",&A,&B,&n)!=EOF)
{
if (A + B + n == 0) break;
f[1]=f[2]=1;
printf("1 1 ");
for(i=3;i<62; i++)
{
f[i] = (A * f[i-1] + B *f[i-2]) % 7;
printf("%d",f[i]);
if(i%10==0)
printf("\n");
}
}
return 0;
}
这里很清晰就可以看出重复的情况,的确是存在的,而且我设置了10个数值换一行,可以很方便算出来周期的值48,1~48是一个周期。
总结
1:数学题一般都是可以找规律的
2:凡是求模的题目答案一般都是周期性的
3:周期可以通过不严谨的代码查找
4:周期也可以通过打印输出自己来找