hdoj-1005 找规律

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
 
第一眼感觉这道题应该用递归,太简单了。但是事情肯定不会像想象中那么简单,Memory Limit Exceeded出现了,再仔细的去分析下题目,N实在是太大了
那么这道题目,应该是有规律可循。这个序列总是跟前两个数相关,那么只要出现相同连续的两个数就肯定会有重复。而被7除的余数只能是0-6,两个的序列是49,即最大循环周期是49.。49次过后肯定会出现重复,那么N大于49的部分就不用计算了,直接代入N%7就行了。
 
 
下面是java的实现
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner ss=new Scanner(System.in);
        short a=ss.nextShort();
        short b=ss.nextShort();
        int n=ss.nextInt();
        while (a!=0 && b!=0 && n!=0) {
            System.out.println(f(n%49, a, b));
            a=ss.nextShort();
            b=ss.nextShort();
            n=ss.nextInt();
        }
        ss.close();
    }
    private static byte f(int n,short a,short b)
    {
        if(n==1)
            return 1;
        if(n==2)
            return 1;
        return (byte)((f(n-1, a, b)*a+f(n-2, a, b)*b)%7);
    }
}
 
 
原文地址:https://www.cnblogs.com/maydow/p/4498868.html