Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 188565 Accepted Submission(s): 47058
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
—————————————————————————
由于有一个模7,所以我们猜想这个数列会循环,什么时候循环一次?当1 1第二次出现的时候就证明开始循环了,所以我们要找第二个1 1
注意:数组大小,循环的条件不要设的太大,会出错,为什么会出错?
我也不知道= =!
————————————————————————
源码;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
int a = scanner.nextInt();
int b = scanner.nextInt();
int n = scanner.nextInt();
if(a==0 && b==0 && n==0)
System.exit(0);
if(a==0 && b==0)
{
System.out.println(0);
continue;
}
int i =0;
int[] result = new int[100000];
result[0]=1;
result[1]=1;
for(i = 2 ;i < 1000 ; i++)
{
result[i]=(a*result[i-1]+b*result[i-2])%7;
if(result[i-2] == 1 && result[i-1] == 1 && i != 2) break;
}
System.out.println(result[(n-1)%(i-2)]);
}
}
}