码迷,mamicode.com
首页 > 其他好文 > 详细

hdoj-1005 找规律

时间:2015-05-13 00:37:00      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

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);
    }
}

 

 
 

hdoj-1005 找规律

标签:

原文地址:http://www.cnblogs.com/maydow/p/4498868.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!