Number Sequence

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
 
这道题完全不知道如何找规律,直接用递归会爆栈,最后是看的网上大神总结的周期
AC代码:
 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner sc = new Scanner(System.in);
 6         while (sc.hasNext()) {
 7             int a = sc.nextInt();
 8             int b = sc.nextInt();
 9             int n = sc.nextInt();
10             if (a < 1 & a > 1000 & b < 1 & b > 1000 & b < 1 & a > 100000000)
11                 break;
12             if (a == 0 & b == 0 & n == 0)
13                 break;
14             int f[] = new int[49];
15             for (int i = 1; i < 49; i++) {  //通过大神总结出来的周期,直接用递归会爆栈
16                 if (i == 1 || i == 2) {
17                     f[i] = 1;
18                 } else {
19                     f[i] = (a * f[i - 1] + b * f[i - 2]) % 7;
20                 }
21             }
22             System.out.println(f[n % 49]);
23         }
24 
25     }
26 }

 

posted @ 2017-12-13 17:18  ixummer  阅读(639)  评论(0编辑  收藏  举报