Skip to content

Instantly share code, notes, and snippets.

@baniol
Created September 15, 2014 06:36
Show Gist options
  • Save baniol/bc022e272d6a8460c9ba to your computer and use it in GitHub Desktop.
Save baniol/bc022e272d6a8460c9ba to your computer and use it in GitHub Desktop.
Greatest Common Divisor, recursive & iterative
// recursive
var gcd = function(a, b) {
if ( ! b) {
return a;
}
return gcd(b, a % b);
};
// iterative
function gcd(a,b) {
if (a < 0) a = -a;
if (b < 0) b = -b;
if (b > a) {var temp = a; a = b; b = temp;}
while (true) {
a %= b;
if (a == 0) return b;
b %= a;
if (b == 0) return a;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment