Skip to content

Instantly share code, notes, and snippets.

@denmch
Created December 22, 2015 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denmch/0accef11b5ca64aac838 to your computer and use it in GitHub Desktop.
Save denmch/0accef11b5ca64aac838 to your computer and use it in GitHub Desktop.
"Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters."
// Callback to calculate the Greatest Common Divisor,
// used within the scm callback.
function gcd(a, b) {
if (!b) {
return a;
}
return gcd(b, a % b);
}
// Callback to calculate the Smallest Common Multiple,
// used within the main program.
function scm(a, b) {
return a * b / gcd(a,b);
}
// This is the crux of the biscuit:
function smallestCommons(arr) {
var sortedArr = [], // Initialize some variables
tmpArr = [],
result = [];
sortedArr = arr.sort(function(a, b) { // Define the sortedArr
return a - b; // Sort ascending
});
for (i = 1; i <= (sortedArr[1] - sortedArr[0] + 1); i++) {
tmpArr.push(i); // Generate tmpArr and prepare it for the result
}
result = tmpArr.reduce(function (a, b) {
return scm(a, b); // Reduce the sortedArr using the scm callback
});
return result;
}
smallestCommons([1,5]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment