Last active
September 9, 2016 10:46
-
-
Save nkapliev/87f64191f89aa108524b50398cc9a1d9 to your computer and use it in GitHub Desktop.
Greatest common divisor in Javascript @see: https://en.wikipedia.org/wiki/Binary_GCD_algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var gcd = function(a, b) { | |
var coef = 1; | |
while ( | |
a !== b && | |
a !== 0 && | |
b !== 0 && | |
a !== 1 && | |
b !== 1 | |
) { | |
if ( ! (a % 2) && ! (b % 2)) { | |
coef *= 2; | |
a /= 2; | |
b /= 2; | |
} else if ( ! (a % 2)) { | |
a /= 2; | |
} else if ( ! (b % 2)) { | |
b /= 2; | |
} else if (a > b) { | |
a = (a - b) / 2; | |
} else if (b > a) { | |
b = (b - a) / 2; | |
} | |
} | |
return coef * ((a === 1 || b === 1) ? 1 : (a || b)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment