矩阵快速幂(矩阵连乘)

矩阵快速幂的本质还是快速幂,是解决高次幂取模的问题的一种形式,他适用于有矩阵高次幂的运算我们以hdu1021为例

Fibonacci Again

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 61948    Accepted Submission(s): 28920


Problem Description
There are another kind of Fibonacci numbers: F(0) = 7, F(1) = 11, F(n) = F(n-1) + F(n-2) (n>=2).
 

Input
Input consists of a sequence of lines, each containing an integer n. (n < 1,000,000).
 

Output
Print the word "yes" if 3 divide evenly into F(n).

Print the word "no" if not.
 

Sample Input

0 1 2 3 4 5
 

Sample Output

no no yes no no no
 
题目求F(n)是否能被3整除,而  F(n) = F(n-1) + F(n-2)由此表达式构造一个矩阵


然后只要计算出矩阵

的值那么f(n)=a[0][0]*f(1)+a[0][1]*f(0)

首先矩阵的乘法为

Matrix Matrixmul(Matrix a,Matrix b)
{
    int i,j,k;
    Matrix c;
    for(i=0;i
在快速幂中需要进行矩阵的乘法即此算法,对应的快速幂中的当n%2==1时我们要将答案乘上一个a矩阵,这个时候我们需要单位矩阵来参与乘法

你的公式中的矩阵为几阶单位矩阵为几阶

Matrix quickpow(long long n)
{
    Matrix m=P,b=I;//b为单位矩阵
    while(n>0)
    {
        if(n%2==1)
            b=Matrixmul(b,m);
        n=n/2;
        m=Matrixmul(m,m);
    }
    return b;
}
对于矩阵的取模在矩阵的乘法里面

附上完整代码

#include 
#include 
#include 
#include 
#define MAX 2
using namespace std;
typedef struct {
int m[MAX][MAX];
}Matrix;
Matrix P={1,1,1,0};
Matrix I={1,0,0,1};
Matrix Matrixmul(Matrix a,Matrix b)
{
    int i,j,k;
    Matrix c;
    for(i=0;i0)
    {
        if(n%2==1)
            b=Matrixmul(b,m);
        n=n/2;
        m=Matrixmul(m,m);
    }
    return b;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0) printf("no\n");
        else if(n==1)
        printf("no\n");
        else
        {
            Matrix a;
            a=quickpow(n-1);
            if((a.m[0][0]*11+a.m[0][1]*7)%3==0)
                printf("yes\n");
            else
                printf("no\n");
        }
    }
    return 0;
}
对于推矩阵方程我们可以得到一些规律

F(n)=F(n-1)+F(n-2)+F(n-3)+....,F(n)的表达式后有几项,所对应的矩阵方程也为几阶,且第一次的列表达式为F(n)后的几项



对这两个表达式再想想

你可能感兴趣的:(数论)