Number Sequence HDU-1005

版权声明:欢迎转载 https://blog.csdn.net/hqzzbh/article/details/79962154

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

#include<iostream>
using namespace std;
int main()
{
    int a, b, n;
    int f[50]; //因为 f[n]是%7后得出的结果,而%7后有7种结果0,
    //1,2,3,4,5,6;f(n-1)有7种可能,
    //f(n-2)有7种可能; (f[n-1],f[n-2])出现重复的组合的最大周期为7*7=49
    while (cin >> a >> b >> n && a && b && n)
    {
        if (n == 1 || n == 2)
        {
            cout << "1" << endl; continue;
        }   
        for (int i = 1; i < 3; i ++)
            f[i] = 1;
        for (int i = 3; i <= n % 49; i ++)
            f[i] = (a * f[i-1] + b * f[i-2]) % 7; 
        cout << f[n%49] << endl;
    }
    return 0;
}
阅读更多

没有更多推荐了,返回首页