题目是这样的:
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
首先,我来说说关于我的思路,我是通过找规律找周期来做的,但是做的时候要到了问题,我总是以为,周期的开头值必须是1,结果,就陷入了错误之中,并且无法自拔,
看了大量的博客之后,才知道如何去修改。(简单说说吧,就是周期的开头值不一定是1)
还不明白的,可以看看我的代码。
先看看我错误的代码吧:
package package1;
import java.util.Scanner;
public class Main
{
public static int A,B,n;
public static final int Maxn = 100;
public static int[] Arr = new int[Maxn];
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
while(cin.hasNext())
{
A = cin.nextInt();
B = cin.nextInt();
n = cin.nextInt();
if(A == 0 && B == 0 && n == 0)
{
return;
}
int T;
T = init();
Arr[0] = Arr[T];
System.out.println(Arr[n%T]);
}
}
public static int init()
{
Arr[1] = 1;
Arr[2] = 1;
int i;
for(i = 3 ; i < Maxn ; i++)
{
Arr[i] = (A * Arr[i-1] + B * Arr[i-2])%7;
if(Arr[i-1] == 1 && Arr[i] == 1)
{
break;
}
}
return (i - 2);
}
}
修改之后的代码实现如下: