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
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MM=2;
const int mod=7;
struct node
{
int ma[MM][MM];
};
node kuaipow(node a,node b)//矩阵乘法//a的行乘以b的列
{
node ans;
for(int i=0; i<MM; i++)
{
for(int j=0; j<MM; j++)
{
ans.ma[i][j]=0;
for(int k=0; k<MM; k++)
{
ans.ma[i][j]+=(a.ma[i][k]*b.ma[k][j])%mod ;//
ans.ma[i][j]%=mod;
}
}
}
return ans;
}
node pow(node a,int b)//矩阵快速幂//
{
node ans;
for(int i=0; i<MM; i++)
{
for(int j=0; j<MM; j++)
{
ans.ma[i][j]=0;
}
for(int i=0;i<MM;i++)
{
ans.ma[i][i]=1;
}
}
while(b)
{
if(b&1)
ans=kuaipow(ans,a);
b>>=1;
a=kuaipow(a,a);
}
return ans;
}
int main()
{
int n,A,B;
node s;
while(scanf("%d%d%d",&A,&B,&n))
{
if(A==0||B==0||n==0)
break;
//构造一个新的矩阵
//矩阵s
/*1 1
1 0*/
s.ma[0][0]=A;
s.ma[0][1]=B;
s.ma[1][0]=1;
s.ma[1][1]=0;
if(n==1||n==2)
{
printf("1\n");
}
else
{
node tmp=pow(s,n-2);//这里我们是n-2
int as=(tmp.ma[0][0]+tmp.ma[0][1])%7;
printf("%d\n",as);
}
}
return 0;
}