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.
闲谈:这个题很早就做过了,第一次做用的规律。后来知道还能用矩阵快速幂解,就学了一下又做了一遍。讲一下矩阵快速幂的做法
题解:
题目给你了公式,区别于一般的矩阵快速幂,他给的系数是A,B。我们就来推导一下。
f(n)=A*f(n-1)+B*f(n-2)
f(n+1)=A*f(n)+B*f(n-1)=A^2*f(n-1)+A*Bf(n)*f(n-2)+B*f(n-1);
把基础的:
1 1
1 0
换成
a b
1 0
得到新公式:
让A=
所以f(n)=(A[0][0]+A[0][1])mod7;
代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
const int MAX_N=1e8+100;
const int mod=7;
struct mat
{
int M[2][2];
};
int a,b,n;
mat mat_mul(mat x,mat y)
{
mat res;
memset(res.M,0,sizeof(res.M));
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
{
res.M[i][j]+=x.M[i][k]*y.M[k][j];
res.M[i][j]%=mod;
}
return res;
}
int mod_pow(int N)
{
mat c,res;
memset(res.M,0,sizeof(res.M));
c.M[0][0]=a; c.M[0][1]=b;
c.M[1][0]=1; c.M[1][1]=0;
for(int i=0;i<2;i++)
res.M[i][i]=1;
while(N>0)
{
if(N&1) res=mat_mul(res,c);
c=mat_mul(c,c);
N>>=1;
}
return res.M[0][0]+res.M[0][1];
}
int main()
{
while(scanf("%d%d%d",&a,&b,&n)&&a)
{
int d=mod_pow(n-2)%mod;
printf("%d\n",d);
}
return 0;
}