Skip to content

Instantly share code, notes, and snippets.

@farskid
Last active October 24, 2017 07:54
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 farskid/5ab17033e757b4e7a2b45db24f70d6c8 to your computer and use it in GitHub Desktop.
Save farskid/5ab17033e757b4e7a2b45db24f70d6c8 to your computer and use it in GitHub Desktop.
Find the Greatest Common Divisor of two numbers
function gcd(n, m) {
if (!m) { return n; }
return (m, n % m);
}
console.log(gcd(512, 1024)); // 256
function isEven(num) {
return num % 2 === 0;
}
function findDevisors(num) {
var result = [], max = isEven(num) ? num / 2 : Math.floor(num / 2);
for (var i = 2; i <= max; i++) {
if (num % i === 0) {
result.push(i);
}
}
return result;
}
function commonTwoArrays(a, b) {
var result = [];
a.forEach(function(item) {
if (b.indexOf(item) !== -1) {
result.push(item);
}
});
return result;
}
function gcd(n, m) {
var nList = findDevisors(n);
var mList = findDevisors(m);
var commonList = commonTwoArrays(nList, mList);
return Math.max.apply(null, commonList);
}
console.log(gcd(512, 1024)); // 256
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment