![]() |
VOOZH | about |
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 :
- Generate an n × 1 random 0/1 vector r?.
- Compute P? = A × (Br)? - Cr?.
- 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:
Yes
Time Complexity: O(N ^ 2)
Auxiliary Space: O(N )