1049. Ledger Matrix Product
A bank keeps two ledgers as matrices of very large integers. Matrix a has n rows and m columns, matrix b has m rows and p columns, and the combined report is their matrix product: entry (i, j) is the sum over k of a[i][k] * b[k][j].
The true numbers are far too large to store, so every entry of the result must be reported modulo 1,000,000,007 and lie in the range 0 to 1,000,000,006. Individual products overflow 64-bit integers if the inputs are not reduced first, so reduce before multiplying and reduce again while summing. Use the standard triple loop in O(n*m*p) time.
Example 1
- Input:
- a = [[1,2],[3,4]], b = [[5,6],[7,8]]
- Output:
- [[19,22],[43,50]]
- Explanation:
The product is [[19, 22], [43, 50]] and every value is already below the modulus.
Example 2
- Input:
- a = [[1000000006,2]], b = [[2],[3]]
- Output:
- [[4]]
- Explanation:
The single entry is 1000000006*2 + 2*3 = 2000000018, which is 1000000004 after subtracting the modulus twice.
Constraints
1 ≤ n, m, p ≤ 30 (a is n x m, b is m x p), and n * m, m * p ≤ 250
0 ≤ a[i][k], b[k][j] ≤ 1015
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n*m*p)
- Space
- O(n*p)