[ACM]Number Sequence

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

Author

CHEN, Shunbao

Source

ZJCPC2004


解题思路:

一开始用了一个很大的数组num[100000005],每次利用公式f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.在数组中保存n个数,结果最后提交内存溢出。后来又想,不能开这么大的数组,考虑规律,循环的情况,开始是f(1)=1,f(2)=1,因此当在计算过程中再次出现两个连续的1时,循环就发现了,因为f(n)是对7取余得到的,所以f(n)的可能取值为0,1,2,3,4,5,6,共七个数,,循环周期不会超过49,所以可以开一个小点的数组,下面代码为[51]。


代码:

#include <iostream>
using namespace std;
int f[51];
int main()
{
    int A,B,n,i;
    while(cin>>A>>B>>n&&A&&B&&n)
    {
        if(n==1||n==2)
            cout<<1<<endl;//特殊情况优先考虑
        else
        {
            f[1]=1;
            f[2]=1;
            for(i=3;i<=50;i++)//注意这里i<= 的数要小于等于50,否则会出现地址非法访问错误
            {
                f[i]=(A*f[i-1]+B*f[i-2])%7;
                if(f[i]==1&&f[i-1]==1)
                break;
            }
            if(i<n)
            {
            i=i-2;  //i为周期
            n=n%i;  //一个周期的第几个数
            if(n==0)
                n=i; //一个周期的最后一个数
            }
            cout<<f[n]<<endl;
        }
    }
    return 0;
}

运行截图:



posted @ 2013-09-01 12:48  同学少年  阅读(261)  评论(0编辑  收藏  举报