Created
December 22, 2015 00:01
-
-
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."
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
// 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