Stein 's Algorithm for finding GCD | Function to implement Stein 's Algorithm ; GCD ( 0 , b ) == b ; GCD ( a , 0 ) == a , GCD ( 0 , 0 ) == 0 ; look for factors of 2 if ( ( ~ a & 1 ) == 1 ) a is even ; if ( ( b & 1 ) == 1 ) b is odd ; else both a and b are even ; a is odd , b is even ; reduce larger number ; Driver Code
function gcd ( a , b ) { if ( a == b ) return a ; if ( a == 0 ) return b ; if ( b == 0 ) return a ; { return gcd ( a >> 1 , b ) ; return gcd ( a >> 1 , b >> 1 ) << 1 ; } if ( ( ~ b & 1 ) == 1 ) return gcd ( a , b >> 1 ) ; if ( a > b ) return gcd ( ( a - b ) >> 1 , b ) ; return gcd ( ( b - a ) >> 1 , a ) ; } let a = 34 , b = 17 ; document . write ( " " + " " + gcd ( a , b ) ) ;