Number Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 109021    Accepted Submission(s): 26499



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​

 


Recommend

JGShining   |   We have carefully selected several similar problems for you:   ​​1008​​​  ​​​1002​​​  ​​​1009​​​  ​​​1012​​​  ​​​1071​​ 

 

解析:首先,观察数据范围,1<=n<=10^8,直接用f[n]来记录是不行的,会爆空间。那么,我们就要考虑一下能否找找规律。

f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

在这里我们用xi代表f[i],f[i+1]组成的排列(f[i]在前,f[i+1]在后)。


由这个递推公式我们可以得出两点:

①x(n-2)决定了f[m](m>=n)的值,换句话说,如果存在i<j,xi==xj,则从i到j-1构成一个循环。

②这个数列是存在循环的,且循环长度一定小于等于49;

    由题可知,0<=f[i]<=6,那么f[i]、f[i+1]可能构成的排列一共只有49种,即xi只有49种情况。

    由此可以推论出:对于x50,必然存在1<=i<=49,使得xi==x50。

    证明:

        命题一:若对于任意的1<=i<j<=49,xi!=xj,也就是说,前49个排列全都是不相同的,那么一定存在xi==x50。

                      用反证法:假设不存在xi==x50,则不相同的排列就有50种。在前面已经提到过,不相同排列最多只有49种,矛盾,故命题成立。

        命题二:若存在1<=i<j<=49,xi==xj,则一定存在x(y)==x50(1<=y<=49);

                      前面已经提过,若存在xi==xj(i!=j),则从i 到 j-1 就构成一个循环。若命题二的假设成立,则在前49个xi中,必存在一个循环节,设循环节的起点为s,长度为len,则一定有1<=s<=y<=s+len-1<=49,y+n*len==50,x(y)==x50,命题二得证。

对于x50,必然存在1<=i<=49,使得xi==x50。

   有了这两点,解题思路也就很明晰了。从1到49循环,若有xi==x50,则循环起点为s=i,len=50-i+1。

代码如下:

#include<cstdio>
using namespace std;

int f[1000],a,b,n,s,len;

void init()
{
freopen("hdu1005.in","r",stdin);
freopen("hdu1005.out","w",stdout);
}

void work()
{
int i,j,k,s,len;
f[1]=f[2]=f[0]=1;
while(scanf("%d%d%d",&a,&b,&n)==3,a)
{
for(i=3;i<=70;i++)f[i]=(f[i-1]*a+f[i-2]*b)%7;
for(i=1;i<=49;i++)if(f[i]==f[50] && f[i+1]==f[51]){s=i,len=50-i;break;}

if(n<s)printf("%d\n",f[n]);
else printf("%d\n",f[(n-s+1)%len+s-1]);
}
}

int main()
{
init();
work();
return 0;
}