Skip to content

Instantly share code, notes, and snippets.

@Narshe1412
Created December 17, 2015 18:17
Show Gist options
  • Save Narshe1412/2ac2f3034521aaf0e0c9 to your computer and use it in GitHub Desktop.
Save Narshe1412/2ac2f3034521aaf0e0c9 to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/narshe1412 's solution for Bonfire:Smallest Common Multiple
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