Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Last active October 13, 2018 18:11
Show Gist options
  • Select an option

  • Save leandrosilva/76115b981e077407f8d573773ebc3b7d to your computer and use it in GitHub Desktop.

Select an option

Save leandrosilva/76115b981e077407f8d573773ebc3b7d to your computer and use it in GitHub Desktop.
Imperative style solution of the GCD problem
function gcd(numbers) {
let results = {};
for (let i = 0; i < numbers.length; i++) {
let divisor = numbers[i];
for (let j = 0; j < numbers.length; j++) {
let number = numbers[j];
if (number == divisor) continue;
let result = number % divisor;
if (result === 0) {
if (results[divisor] === undefined) results[divisor] = 1;
else results[divisor] += 1;
}
}
}
let greatest;
let maxTimes = 0;
for (let divisor in results) {
let times = results[divisor];
if (times > maxTimes) {
greatest = divisor;
maxTimes = times;
}
}
return greatest;
}
function testGCD() {
let nbs;
let rst;
console.log(`1st test >>`);
nbs = [2, 5, 6, 8, 10];
rst = gcd(nbs);
console.log(`[${nbs}] == 2 [${rst == 2}]`);
console.log(`\n2nd test >>`);
nbs = [1, 2, 5, 8, 10, 12, 15];
rst = gcd(nbs);
console.log(`[${nbs}] == 1 [${rst == 1}]`);
console.log(`\n3rd test >>`);
nbs = [2, 3, 5, 6, 9, 10, 12, 15, 18];
rst = gcd(nbs);
console.log(`[${nbs}] == 3 [${rst == 3}]`);
}
testGCD();
@leandrosilva
Copy link
Author

Expected result of this code should be like...

$ node gcd.js
1st test >>
[2,5,6,8,10] == 2 [true]

2nd test >>
[1,2,5,8,10,12,15] == 1 [true]

3rd test >>
[2,3,5,6,9,10,12,15,18] == 3 [true]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment