HDOJ 1005 Java 答案

HDOJ 1005

Problem Description

数字序列定义如下:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
给定A,B和n,你要计算fn)的值。

Input

输入由多个测试用例组成。每个测试用例在一行中包含3个整数A,B和n (1 <= A,B <= 10001 <= n <= 100,000,000)。三个零表示输入结束,此测试用例不进行处理。

Output

对于每个测试用例,在一行上打印f(n)的值。

code

import java.util.*;
import java.io.*;
public class HDOJ1005{

    public static void main(String[] args) throws Exception{
        Scanner cin = new Scanner(System.in);
        int a = cin.nextInt();
        int b = cin.nextInt();
        int n = cin.nextInt();

        while(a != 0 && b != 0 && n != 0 ){
            System.out.println(fun(a,b,n%48));
            a = cin.nextInt();
            b = cin.nextInt();
            n = cin.nextInt();
        }

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

解析

f(n) 的值域是0-6
所以f(n)是循环的。

因为 f(n) = (A * f(n - 1) + B * f(n - 2)) 因为A * f(n - 1) 有7中结果。
所以 f(n)有 7 × 7 =49中结果
又因为起始值是从1开始的
所以排除掉 f(n) = (A * 0 + B * 0) 的可能,
所以周期是48。

猜你喜欢

转载自blog.csdn.net/u013451048/article/details/56489600