矩阵快速幂

文章介绍了如何使用C++编程语言实现矩阵的乘法运算以及快速幂算法,特别提及了斐波那契矩阵的应用。程序展示了矩阵乘法的函数定义、快速幂的计算过程,并在`main`函数中处理用户输入,用于求解特定矩阵的幂和斐波那契矩阵的第n项。
摘要由CSDN通过智能技术生成

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int mod=1000000007;
struct matrix{
    LL c[101][101];
    matrix(){memset(c, 0, sizeof c);}
} A, res;
LL n, k;
matrix operator*(matrix &x, matrix &y){ //矩阵乘法
    matrix t; //临时矩阵
    for(int i=1; i<=n; i++)
      for(int j=1; j<=n; j++)
        for(int k=1; k<=n; k++)    
          t.c[i][j]=(t.c[i][j]+x.c[i][k]*y.c[k][j])%mod;
    return t;
}
void quickpow(LL k){ //快速幂
    for(int i=1; i<=n; i++) res.c[i][i]=1; //单位矩阵
    while(k){
        if(k & 1) res = res*A;
        A = A*A;
        k >>= 1;
   }
}
int main(){
    scanf("%d%lld",&n,&k);
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++)
            scanf("%d",&A.c[i][j]);
    quickpow(k);        
    for(int i=1; i<=n; i++){
        for(int j=1; j<=n; j++)
            printf("%d ",res.c[i][j]);
        puts("");
    }
    return 0;
}

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

typedef long long LL;
const int mod=1000000007;
struct matrix{
  LL c[3][3];
  matrix(){memset(c, 0, sizeof c);}
} F, A; //F为斐波那契矩阵,A为构造矩阵

matrix operator*(matrix &a, matrix &b){ //矩阵乘法
  matrix t; //临时矩阵
  for(int i=1; i<=2; ++i)
    for(int j=1; j<=2; ++j)
      for(int k=1; k<=2; ++k)
        t.c[i][j]=(t.c[i][j]+a.c[i][k]*b.c[k][j])%mod;
  return t;
}
void quickpow(LL n){ //快速幂
  F.c[1][1]=F.c[1][2]=1;
  A.c[1][1]=A.c[1][2]=A.c[2][1]=1;
  while(n){
    if(n & 1) F = F*A;
    A = A*A;
    n >>= 1;
  }
}
int main(){
  LL n; cin>>n;
  if(n<=2){puts("1"); return 0;}
  quickpow(n-2);
  cout << F.c[1][1];
  return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值