VOOZH about

URL: https://www.geeksforgeeks.org/dsa/freivalds-algorithm/

⇱ Freivald’s Algorithm to check if a matrix is product of two - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Freivald’s Algorithm to check if a matrix is product of two

Last Updated : 14 Feb, 2023

Given three matrices A, B and C, find if C is a product of A and B. 
Examples: 

Input : A = 1 1
 1 1
 B = 1 1
 1 1
 C = 2 2
 2 2
Output : Yes
C = A x B

Input : A = 1 1 1
 1 1 1
 1 1 1
 B = 1 1 1
 1 1 1
 1 1 1
 C = 3 3 3
 3 1 2
 3 3 3 
Output : No

A simple solution is to find product of A and B and then check if product is equal to C or not. A possible time complexity of this method is O(n2.8874) using Stression's matrix multiplication

Freivalds' algorithm is a probabilistic randomized algorithm that works in time O(n2) with high probability. In O(kn2) time the algorithm can verify a matrix product with probability of failure less than 2-k. Since the output is not always correct, it is a Monte Carlo randomized algorithm.

Steps : 

  1. Generate an n × 1 random 0/1 vector r?.
  2. Compute P? = A × (Br)? - Cr?.
  3. Return true if P? = ( 0, 0, …, 0 )T, return false otherwise.

The idea is based on the fact that if C is actually a product, then value of A × (Br)? - Cr? will always be 0. If the value is non-zero, then C can not be a product. The error condition is that the value may be 0 even when C is not a product.

Below is the implementation of the above approach:


Output: 
Yes

 

Time Complexity: O(N ^ 2)
Auxiliary Space: O(N ) 

Comment
Article Tags:
Article Tags: