矩阵乘法及矩阵链乘的快速幂优化

 一、矩阵乘法

 1 struct datatype
 2 {
 3     int a[2][2];
 4 };
 5 datatype multiple(datatype x,datatype y)
 6 {
 7     datatype res;
 8     memset(res.a,0,sizeof(res.a));
 9     for(int i=0;i<=1;i++)
10     {
11         for(int j=0;j<=1;j++)
12         {
13             for(int k=0;k<=1;k++)
14             {
15                 res.a[i][j]+=x.a[i][k]*y.a[k][j];
16             }
17         }
18     }
19     for(int i=0;i<=1;i++)
20     {
21         for(int j=0;j<=1;j++)
22         {
23             res.a[i][j]%=10000;
24         }
25     }
26     return res;
27 }

二、矩阵链乘的快速幂优化

 1 struct datatype
 2 {
 3     int a[2][2];
 4 };
 5 datatype multiple(datatype x,datatype y)
 6 {
 7     datatype res;
 8     memset(res.a,0,sizeof(res.a));
 9     for(int i=0;i<=1;i++)
10     {
11         for(int j=0;j<=1;j++)
12         {
13             for(int k=0;k<=1;k++)
14             {
15                 res.a[i][j]+=x.a[i][k]*y.a[k][j];
16             }
17         }
18     }
19     for(int i=0;i<=1;i++)
20     {
21         for(int j=0;j<=1;j++)
22         {
23             res.a[i][j]%=10000;
24         }
25     }
26     return res;
27 }
28 datatype power(datatype x,int y)
29 {
30     datatype res,t;
31     res.a[0][0]=1;
32     res.a[0][1]=0;
33     res.a[1][0]=0;
34     res.a[1][1]=1;
35     t=x;
36     while(y)
37     {
38         if(y&1)
39         {
40             res=multiple(res,t);
41         }
42         t=multiple(t,t);
43         y>>=1;
44     }
45     return res;
46 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值