Skip to content

Instantly share code, notes, and snippets.

@nkapliev
Last active September 9, 2016 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkapliev/87f64191f89aa108524b50398cc9a1d9 to your computer and use it in GitHub Desktop.
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
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