Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 221645 Accepted Submission(s): 56087
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
构造下转移矩阵就好了
g={a,b
1,0};
AC代码:
#include<bits/stdc++.h>
using namespace std;
int n,a,b;
int g[2][2],t[2][2],s[2][2];
void mul(int a[][2],int b[][2])
{
memset(t,0,sizeof t);
for(int k=0;k<2;k++)
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
t[k][i]=(t[k][i]+a[k][j]*b[j][i])%7;
for(int i=0;i<2;i++) for(int j=0;j<2;j++) a[i][j]=t[i][j];
}
void qmi()
{
while(n)
{
if(n&1) mul(s,g);
n>>=1;
mul(g,g);
}
}
int main()
{
while(cin>>a>>b>>n,a||b||n)
{
g[0][0]=a;
g[0][1]=b;
g[1][0]=1;
g[1][1]=0;
if(n==1||n==2)
{
cout<<1<<endl;
continue;
}
n-=3;
for(int i=0;i<2;i++) for(int j=0;j<2;j++) s[i][j]=g[i][j];
qmi();
cout<<(s[0][0]+s[0][1])%7<<endl;
}
return 0;
}