Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++로 두 행렬의 곱셈 가능 여부를 확인하는 방법

행렬의 곱셈이 가능한 조건

두 행렬은 서로 곱할 수 있을 때 '곱셈 가능(multiplicable)'하다고 합니다. 행렬의 곱셈은 첫 번째 행렬의 열 수가 두 번째 행렬의 행 수와 같을 때만 정의됩니다. 이 조건을 만족하지 못하면 두 행렬의 곱은 계산할 수 없습니다.

예를 들어 다음과 같은 경우를 생각해 볼 수 있습니다.

첫 번째 행렬의 행 수 = 3
첫 번째 행렬의 열 수 = 2

두 번째 행렬의 행 수 = 2
두 번째 행렬의 열 수 = 5

첫 번째 행렬의 열 수(2)와 두 번째 행렬의 행 수(2)가 같으므로 두 행렬은 곱셈이 가능하며, 결과 행렬의 크기는 3×5가 됩니다.

다음은 두 행렬의 곱셈 가능 여부를 확인하는 C++ 프로그램입니다.

예제 코드

#include<iostream>
using namespace std;
int main() {
    int row1, column1, row2, column2;
    cout<<"Enter the dimensions of the first matrix:"<< endl;
    cin>>row1;
    cin>>column1;
    cout<<"Enter the dimensions of the second matrix: "<<endl;
    cin>>row2;
    cin>>column2;
    cout<<"First Matrix"<<endl;
    cout<<"Number of rows: "<<row1<<endl;
    cout<<"Number of columns: "<<column1<<endl;
    cout<<"Second Matrix"<<endl;
    cout<<"Number of rows: "<<row2<<endl;
    cout<<"Number of columns: "<<column2<<endl;
    if(column1 == row2)
    cout<<"Matrices are multiplicable";
    else
    cout<<"Matrices are not multiplicable";
    return 0;
}

실행 결과

Enter the dimensions of the first matrix: 2 3
Enter the dimensions of the second matrix: 3 3
First Matrix
Number of rows: 2
Number of columns: 3

Second Matrix
Number of rows: 3
Number of columns: 3

Matrices are multiplicable

코드 설명

위 프로그램은 다음과 같은 순서로 동작합니다.

1. 행렬의 차원 입력 받기

먼저 사용자로부터 두 행렬의 행 수와 열 수를 차례대로 입력받습니다.

cout<<"Enter the dimensions of the first matrix:"<< endl;
cin>>row1;
cin>>column1;
cout<<"Enter the dimensions of the second matrix: "<<endl;
cin>>row2;
cin>>column2;

2. 입력된 차원 출력하기

입력받은 값이 올바른지 확인할 수 있도록 각 행렬의 행 수와 열 수를 화면에 출력합니다.

cout<<"First Matrix"<<endl;
cout<<"Number of rows: "<<row1<<endl;
cout<<"Number of columns: "<<column1<<endl;
cout<<"Second Matrix"<<endl;
cout<<"Number of rows: "<<row2<<endl;
cout<<"Number of columns: "<<column2<<endl;

3. 곱셈 가능 여부 판별하기

if-else 문을 사용하여 첫 번째 행렬의 열 수(column1)와 두 번째 행렬의 행 수(row2)를 비교합니다. 두 값이 같으면 "Matrices are multiplicable"(곱셈 가능)을, 그렇지 않으면 "Matrices are not multiplicable"(곱셈 불가능)을 출력합니다.

if(column1 == row2)
cout<<"Matrices are multiplicable";
else
cout<<"Matrices are not multiplicable";

이처럼 column1 == row2 조건 하나만 검사하면 되므로 이 확인 과정의 시간 복잡도는 O(1)입니다. 또한 곱셈이 가능한 경우 결과 행렬의 크기는 '첫 번째 행렬의 행 수 × 두 번째 행렬의 열 수'가 된다는 점도 함께 기억해 두면 좋습니다.