Matrix Multiplication
Completed
Read an n×m matrix A and an m×p matrix B and print A×B.
Input
n m, A's rows, then m p, B's rows.
Output
n rows of p numbers.
Example
Input
2 2 1 2 3 4 2 2 5 6 7 8
Output
19 22 43 50
Editor
Java
Hints
Cell (i, j) is the sum over k of a[i][k] * b[k][j].
Solution explanation
Three nested loops: rows of A, columns of B, and the shared dimension.
Show solution
import java.util.Scanner;
public class Main {
static int[][] read(Scanner sc) {
int r = sc.nextInt(), c = sc.nextInt();
int[][] m = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
m[i][j] = sc.nextInt();
}
}
return m;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] a = read(sc);
int[][] b = read(sc);
for (int i = 0; i < a.length; i++) {
StringBuilder row = new StringBuilder();
for (int j = 0; j < b[0].length; j++) {
int sum = 0;
for (int k = 0; k < b.length; k++) {
sum += a[i][k] * b[k][j];
}
row.append(sum).append(j < b[0].length - 1 ? " " : "");
}
System.out.println(row);
}
}
}