Skip to content

Instantly share code, notes, and snippets.

@vadimkorr
Created January 14, 2018 20:23
Show Gist options
  • Save vadimkorr/fc612ee1c139970e04c24faecace8a2d to your computer and use it in GitHub Desktop.
Save vadimkorr/fc612ee1c139970e04c24faecace8a2d to your computer and use it in GitHub Desktop.
//Task: Find the greatest common divisor for an array of integers
//Tags: array, gcd
let arr = [6, 9, 21]
let gcd = function(a, b) {
a = Math.abs(a)
b = Math.abs(b)
while (a != b) {
if (a > b) a -= b
else b -= a
}
return a
}
let gcdArr = function(arr) {
let gcdres = gcd(arr[0], arr[1])
for (let i=3; i<arr.length; i++) {
gcdres = gcd(gcdres, arr[i])
}
return gcdres
}
console.log(gcdArr(arr))
@ygoe
Copy link

ygoe commented Apr 10, 2021

What about arr[2]? That seems to be ignored.

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