Last active
October 13, 2018 18:11
-
-
Save leandrosilva/76115b981e077407f8d573773ebc3b7d to your computer and use it in GitHub Desktop.
Imperative style solution of the GCD problem
This file contains 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
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expected result of this code should be like...