Freivaldâ €™ s Algorithm to check if a matrix is product of two | JavaScript code to implement FreivaldaTMs Algorithm ; Function to check if ABx = Cx ; Generate a random vector ; Now comput B * r for evaluating expression A * ( B * r ) - ( C * r ) ; Now comput C * r for evaluating expression A * ( B * r ) - ( C * r ) ; Now comput A * ( B * r ) for evaluating expression A * ( B * r ) - ( C * r ) ; Finally check if value of expression A * ( B * r ) - ( C * r ) is 0 or not ; Runs k iterations Freivald . The value of k determines accuracy . Higher value means higher accuracy . ; Driver code
let N = 2 ; function freivald ( a , b , c ) { let r = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) r [ i ] = Math . random ( ) % 2 ; let br = new Array ( N ) ; br . fill ( 0 ) ; for ( let i = 0 ; i < N ; i ++ ) for ( let j = 0 ; j < N ; j ++ ) br [ i ] = br [ i ] + b [ i ] [ j ] * r [ j ] ; let cr = new Array ( N ) ; cr . fill ( 0 ) ; for ( let i = 0 ; i < N ; i ++ ) for ( let j = 0 ; j < N ; j ++ ) cr [ i ] = cr [ i ] + c [ i ] [ j ] * r [ j ] ; let axbr = new Array ( N ) ; axbr . fill ( 0 ) ; for ( let i = 0 ; i < N ; i ++ ) for ( let j = 0 ; j < N ; j ++ ) axbr [ i ] = axbr [ i ] + a [ i ] [ j ] * br [ j ] ; for ( let i = 0 ; i < N ; i ++ ) if ( axbr [ i ] - cr [ i ] != 0 ) false ; return true ; } function isProduct ( a , b , c , k ) { for ( let i = 0 ; i < k ; i ++ ) if ( freivald ( a , b , c ) == false ) return false ; return true ; } let a = [ [ 1 , 1 ] , [ 1 , 1 ] ] ; let b = [ [ 1 , 1 ] , [ 1 , 1 ] ] ; let c = [ [ 2 , 2 ] , [ 2 , 2 ] ] ; let k = 2 ; if ( isProduct ( a , b , c , k ) ) document . write ( " " ) ; else document . write ( " " ) ;