Created
January 14, 2018 20:23
-
-
Save vadimkorr/fc612ee1c139970e04c24faecace8a2d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about
arr[2]
? That seems to be ignored.