# HDU 1005 Number Sequence（矩阵乘法+快速幂）

## 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.

## 题解

### 矩阵乘法：

[f(n)f(n1)]=[1110][f(n1)f(n2)] [ f ( n ) f ( n − 1 ) ] = [ 1 1 1 0 ] [ f ( n − 1 ) f ( n − 2 ) ]

[f(n1)f(n2)]=[1110][f(n2)f(n3)] [ f ( n − 1 ) f ( n − 2 ) ] = [ 1 1 1 0 ] [ f ( n − 2 ) f ( n − 3 ) ]

[f(n)f(n1)]=[1110][1110][f(n2)f(n3)] [ f ( n ) f ( n − 1 ) ] = [ 1 1 1 0 ] [ 1 1 1 0 ] [ f ( n − 2 ) f ( n − 3 ) ]

[f(n)f(n1)]=[A1B0][f(n1)f(n2)] [ f ( n ) f ( n − 1 ) ] = [ A B 1 0 ] [ f ( n − 1 ) f ( n − 2 ) ]

[f(n)f(n1)]=[A1B0](n2)[f(2)f(1)] [ f ( n ) f ( n − 1 ) ] = [ A B 1 0 ] ( n − 2 ) [ f ( 2 ) f ( 1 ) ]

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;
const int m = 2;
const int mod = 7;
struct Matrix
{
int x[m][m];
};

// 矩阵乘法
Matrix multiplication(Matrix a, Matrix b)
{
Matrix temp;
memset(temp.x, 0, sizeof(temp.x));
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
for(int k=0; k<m; k++)
{
temp.x[i][j] += a.x[i][k] * b.x[k][j];
temp.x[i][j] %= mod;
}
}
}
return temp;
}

//矩阵的快速幂
Matrix powmatrix(Matrix matrix, int n)
{
Matrix temp;
memset(temp.x, 0, sizeof(temp.x));
for(int i=0; i<m; i++)
temp.x[i][i] = 1;     //初始化为单位阵
while(n)
{
if(n%2 == 1)
{
temp = multiplication(temp, matrix);
}
matrix = multiplication(matrix, matrix);
n = n/2;
}
return temp;
}

int main()
{
int A, B;
long long n;
while((cin>>A>>B>>n) && A!=0 && B!=0 && n!=0)
{
Matrix mat;
// 初始条件
mat.x[0][0] = A;
mat.x[0][1] = B;
mat.x[1][0] = 1;
mat.x[1][1] = 0;
mat = powmatrix(mat, n-2);
printf("%d\n",(mat.x[0][0] + mat.x[0][1])%mod);
}
return 0;
}


### 找规律：

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;

int main()
{
int A, B;
long long n;
int f[51];
while((cin>> A >> B >> n) && A!=0 && B!=0 && n!=0)
{
f[1] = 1;
f[2] = 1;
int i;
for(i=3; i<51; i++)
{
f[i] = A*f[i-1] + B*f[i-2];
f[i] = f[i] % 7;
if(f[i] == 1 && f[i-1] == 1)
{
break;
}
}
n = n%(i-2);   // i-2为一个周期
f[0] = f[i-2];
cout << f[n] <<endl;
}
return 0;
}


## 参考链接：

本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。