
Problem
Solution
Submissions
Multiply Two Matrices
Certification: Basic Level
Accuracy: 66.67%
Submissions: 3
Points: 8
Write a C# program to multiply two matrices. Given two matrices A of dimension m×n and B of dimension n×p, calculate their product C of dimension m×p. The matrix multiplication rule states that C[i,j] = sum(A[i,k] * B[k,j]) for k from 0 to n-1.
Example 1
- Input:
Matrix A = [
[1, 2],
[3, 4] ]
Matrix B = [
[5, 6],
[7, 8] ] - Output: [
[19, 22],
[43, 50] ] - Explanation:
- Step 1: Verify matrices can be multiplied by checking if the number of columns in A equals the number of rows in B.
- Step 2: Create a result matrix C with dimensions m×p (rows of A × columns of B).
- Step 3: For each element C[i,j], calculate the sum of products A[i,k] * B[k,j] for all valid k values (0 to n-1).
- Step 4: Calculate each element:
- C[0,0] = A[0,0]*B[0,0] + A[0,1]*B[1,0] = 1*5 + 2*7 = 5 + 14 = 19
- C[0,1] = A[0,0]*B[0,1] + A[0,1]*B[1,1] = 1*6 + 2*8 = 6 + 16 = 22
- C[1,0] = A[1,0]*B[0,0] + A[1,1]*B[1,0] = 3*5 + 4*7 = 15 + 28 = 43
- C[1,1] = A[1,0]*B[0,1] + A[1,1]*B[1,1] = 3*6 + 4*8 = 18 + 32 = 50
Example 2
- Input:
Matrix A = [
[1, 2, 3],
[4, 5, 6] ]
Matrix B = [
[7, 8],
[9, 10],
[11, 12] ] - Output: [
[58, 64],
[139, 154] ] - Explanation:
- Step 1: Verify matrices can be multiplied by checking if the number of columns in A equals the number of rows in B.
- Step 2: Create a result matrix C with dimensions m×p (rows of A × columns of B).
- Step 3: For each element C[i,j], calculate the sum of products A[i,k] * B[k,j] for all valid k values (0 to n-1).
- Step 4: Calculate each element:
- C[0,0] = 1*7 + 2*9 + 3*11 = 7 + 18 + 33 = 58
- C[0,1] = 1*8 + 2*10 + 3*12 = 8 + 20 + 36 = 64
- C[1,0] = 4*7 + 5*9 + 6*11 = 28 + 45 + 66 = 139
- C[1,1] = 4*8 + 5*10 + 6*12 = 32 + 50 + 72 = 154
Constraints
- 1 ≤ A.rows, A.columns, B.rows, B.columns ≤ 100
- A.columns == B.rows (required for matrix multiplication)
- -1000 ≤ A[i][j], B[i][j] ≤ 1000
- Time Complexity: O(m*n*p)
- Space Complexity: O(m*p)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Verify that the number of columns in matrix A equals the number of rows in matrix B.
- Create a result matrix of size m×p.
- Use three nested loops: one for rows in A, one for columns in B, and one for the common dimension.
- Calculate each element of the result matrix using the formula C[i,j] = sum(A[i,k] * B[k,j]) for all k.
- Optimize inner loops for better cache performance if necessary.