FreeCodeCamp: Intermediate Algorithm Scripting: Smallest Common Multiple
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.
The range will be an array of two numbers that will not necessarily be in numerical order.
For example, if given 1 and 3, find the smallest common multiple of both 1 and 3 that is also evenly divisible by all numbers between 1 and 3. The answer here would be 6.
function smallestCommons(arr) {
let orderArr = arr.sort((a,b) => a-b); //arr.sort() works too.
let allArr = [];
let smallest = 0;
for (let i = orderArr[0]; i <= orderArr[orderArr.length - 1]; i++) {
allArr.push(i);
}
while (true) { //use a while loop so the for loop starts at 0 again
smallest++;
for (let i = 0 ; i < allArr.length; i++) {
if (smallest % allArr[i] !== 0) {
break;
}
else if (i === allArr.length - 1) {
return smallest;
}
}
}
}
smallestCommons([1,5]);
Comments
Post a Comment