﻿ 矩阵快速幂

1605: 数字序列

[提交][状态][讨论版][命题人:541307010108]

题目描述

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

```1 1 3
1 2 10
0 0 0```

样例输出

```2
5```

AC：代码

``````#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;

const int maxn = 2;
#define mod 7

struct martix{
int s[2][2];
};

martix mulmartix(martix a,martix b)
{
martix temp;
memset(temp.s,0,sizeof(temp.s));
for(int i = 0;i<maxn;i++){
for(int j = 0;j<maxn;j++){
for(int k = 0;k<maxn;k++){
temp.s[i][j] += a.s[i][k] * b.s[k][j];
temp.s[i][j] = temp.s[i][j]%mod;
}
}
}
return temp;
}

martix powmartix(martix x,int b){
martix a;
memset(a.s,0,sizeof(a.s));
for(int i = 0;i<maxn;i++){
a.s[i][i] = 1;
}
while(b){
if(b&1) a = mulmartix(x,a);
b >>= 1;
x = mulmartix(x,x);
}
return a;
}

int main()
{
int a,b,n;
while(~scanf("%d %d %d",&a,&b,&n))
{
if(a==0&&b==0&&n==0) break;
martix x;
x.s[0][0] = a;
x.s[0][1] = b;
x.s[1][0] = 1;
x.s[1][1] = 0;
martix y = powmartix(x,n-1);
printf("%d
",(y.s[1][0]%mod + y.s[1][1]%mod + mod )%mod);
}

return 0;
}``````