Created
December 17, 2015 18:17
-
-
Save Narshe1412/2ac2f3034521aaf0e0c9 to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/narshe1412 's solution for Bonfire:Smallest Common Multiple
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 smallestCommons(arr) { | |
// Greates common divisor formula | |
function gcd(a, b) { | |
while (b !== 0) { | |
var t = b; | |
b = a % b; | |
a = t; | |
} | |
return a; | |
} | |
// Least common multiple formula (based on GCD) | |
function lcm(a,b) { | |
return a*b/gcd(a,b); | |
} | |
// We determine what's the highest value passed | |
var max, min; | |
/* ---- OLD CODE ----- | |
if (arr[0] > arr[1]) { | |
max = arr[0]; | |
min = arr[1]; | |
} else { | |
max = arr[1]; | |
min = arr[0]; | |
} */ | |
max = Math.max(...arr); //<<- this code only available in ES6 | |
min = Math.min(...arr); | |
// We navigate the numbers, always calculating the LCM from the previous result to the next number | |
// Previous result will always be the LCM from all the previous, per multiplication properties | |
var result = min; | |
for (var i=min; i<= max; i++){ | |
result = lcm(result,i); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment