HDOJ-1005(Java)

Q:

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

Analysis:
基本看了这个题第一个肯定想到的方法是递归,但是n太大了,显然会TLE;只能另辟蹊径:

1.因为公式是f(n) = (A * f(n – 1) + B * f(n – 2)) mod 7,所以f(n)=(A%7*f(n-1)+B%7*f(n-2))%7,A%7与B%7的值的范围只有0~6,也就是说循环体最大是49。那就可以用一个大于49的数组来保存f(n),直到找出循环为止。
2.因为循环的条件就是有2个数m和n
f[m-1] = f[n-1], f[m] = f[n] 这样就会开始循环了。
即f[n-1], f[n]与之前的[m-1],f[m]分别对应
而 0 <= f[n-1],f[n] < 7
所以f[n-1]f[n]连着的情况有7*7的情况。
只需每次求出一个f[n],然后比较f[n-1]f[n]与前面数的情况即可。
所以在一定范围内f[50]就会出现重复——循环节

思路参考自:
思路原博客

Code:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int A,B;
        int n;
        Scanner in=new Scanner(System.in);
        while(in.hasNextInt()) {
            A=in.nextInt();
            B=in.nextInt();
            n=in.nextInt();
            if(A==0&&B==0&&n==0) {
                break;
            }
            //因为周期为49,每次取余即可
            System.out.println(f(n%49,A,B));
        }
    }

    public static int f(int n,int a,int b) {
        if(n==1||n==2) {
            return 1;
        }
        return (a*f(n-1, a, b)+b*f(n-2, a, b))%7;
    }

}

猜你喜欢

转载自blog.csdn.net/renxingkai/article/details/79743063