Given three n x n matrices A, B, and C, verify whether C = A × B using Freivald’s randomized algorithm. The goal is to check the correctness of matrix multiplication much faster than recomputing the product directly.
Instead of computing A × B directly, use a random vector to probabilistically check if C = A × B. If C ≠ A × B, the algorithm will detect the error with high probability after a few iterations.
import random
classSolution:
deffreivalds(self, A: list[list[int]], B: list[list[int]], C: list[list[int]], k: int =10) -> bool:
n = len(A)
for _ in range(k):
r = [random.randint(0, 1) for _ in range(n)]
Br = [sum(B[i][j] * r[j] for j in range(n)) for i in range(n)]
ABr = [sum(A[i][j] * Br[j] for j in range(n)) for i in range(n)]
Cr = [sum(C[i][j] * r[j] for j in range(n)) for i in range(n)]
if ABr != Cr:
returnFalsereturnTrue