【hdu1005】Number Sequence
题目描述
一个数列的定义如下:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
给出A和B,你要求出f(n).
输入
输入包含多个测试案例。每个测试用例包含3个整数A,B和n在一行(1<=A,B≤1000,1≤n≤100000000)。
当输入三个0表示结束
输出
对于每个测试案例,输出f(n),单独占一行。
样例输入
1 1 3
1 2 10
0 0 0
样例输出
2
5
利用矩阵快速幂
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL MOD=7;
LL a, b;
struct mat
{
LL a[2][2];
};
mat mat_mul(mat x,mat y)
{
mat res;
memset(res.a,0,sizeof(res.a));
for(LL i=0; i<2; i++)
for(LL j=0; j<2; j++)
for(LL k=0; k<2; k++)
res.a[i][j]=(res.a[i][j]+x.a[i][k]*y.a[k][j])%MOD;
return res;
}
void mat_pow(LL n)
{
mat c,res;
c.a[0][0]=a, c.a[0][1]=b, c.a[1][0]=1;
c.a[1][1]=0;
memset(res.a,0,sizeof(res.a));
for(LL i=0; i<2; i++) res.a[i][i]=1;
while(n)
{
if(n&1) res=mat_mul(res,c);
c=mat_mul(c,c);
n=n>>1;
}
printf("%lld\n",(res.a[0][0]+res.a[0][1])%MOD);
}
int main()
{
LL n;
while(scanf("%lld%lld%lld", &a, &b, &n), a+b+n)
{
mat_pow(n-2);
}
return 0;
}