首页 > 其他 > 详细

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

时间:2017-09-08 21:34:48      阅读:260      评论:0      收藏:0      [点我收藏+]

 一、矩阵乘法

 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 }

 

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

原文:http://www.cnblogs.com/shao0099876/p/7496193.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!