1. 程式人生 > >HDU-1005-Number Sequence (迴圈週期)

HDU-1005-Number Sequence (迴圈週期)

原題連結:
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
題意:
根據數列遞推公式,求出f(n)。
題解:
這道題目重點是在mod7上,這樣的話很容易就構成迴圈,所以只需要計算他的迴圈週期T,以及T之內的所有結果即可,只不過這道題目好像有多餘限制(T<50),題目題目沒有明確說明,知道這一點就很簡單了。
附上AC程式碼:

#include <iostream>
#include <cstdio>
using namespace std;
#define LL long long
const int mod=7;
const int N=50;
int a,b,n;
int res[50];
int main()
{

    while(scanf("%d %d %d",&a,&b,&n),a||b||n)
    {
        int i;
        res[1]=res[2]=1;
        for(i=3;i<50;i++)//尋找迴圈週期T
        {
            res[i]=(a*res[i-1]+b*res[i-2])%mod;
            if(res[i]==1&&res[i-1]==1)//判斷是否開始新的迴圈
            {
                break;
            }
        }
        int T=i-2;
        if(n%T)
            printf("%d\n",res[n%T]);
        else
            printf("%d\n",res[T]);
    }
    return 0;
}

歡迎評論!