社区讨论
算出来A*A不等与A^2...求教
P3390【模板】矩阵快速幂参与者 6已保存回复 8
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 8 条
- 当前快照
- 1 份
- 快照标识符
- @mi6ls9sy
- 此快照首次捕获于
- 2025/11/20 06:58 4 个月前
- 此快照最后确认于
- 2025/11/20 06:58 4 个月前
代码不是提交的,别喷输入输出。。。
算出来A*A不等与A^2...
CPP#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#define n 2
using namespace std;
struct matrix {
int x[n+1][n+1];
matrix() {
memset(x,0,sizeof(x));
}
void fill(int q) {
int maxx=sizeof(x)/sizeof(int);
int* p=&x[0][0];
while(maxx>0) {
*p=q;
p++;
maxx--;
}
}
};
matrix operator *(matrix a,matrix b)
{
matrix ans;
ans.fill(0);
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
for(int k=1; k<=n; k++) {
ans.x[i][j]+=a.x[i][k]*b.x[k][j];
}
}
}
return ans;
}
matrix operator ^(matrix a,int b)
{
matrix base=a,ans;
ans.fill(1);
while(b) {
if((b&1)!=0) {
ans=ans*base;
}
base=base*base;
b>>=1;
}
return ans;
}
void matrixinput(matrix& a)
{
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
cin>>a.x[i][j];
}
}
}
void matrixoutput(matrix& a)
{
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
cout.width(5);
cout<<a.x[i][j];
}
cout<<endl;
}
}
int main()
{
matrix a,b,c;
cout<<"input A"<<endl;
matrixinput(a);
cout<<"input B"<<endl;
matrixinput(b);
cout<<"answer of A*B"<<endl;
c=a*b;
matrixoutput(c);
int d;
c.fill(1);
cout<<"input power"<<endl;
cin>>d;
c=a^d;
cout<<"answer of A^d"<<endl;
matrixoutput(c);
}
A,B为
1 1
1 1
A*B应该是四个2,然而A^2是4个3
回复
共 8 条回复,欢迎继续交流。
正在加载回复...