Reputation: 415
Question
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.
My Code So Far
function smallestCommons(arr) {
let newArr = [];
let changedArr = arr.sort((a, b)=>{
if(a>b){
return 1;
}
if(b>a){
return -1;
} else {
return 0;
}
})
for(let i = changedArr[0]; i < changedArr[1]; i++){
newArr.push(i);
}
let answer = changedArr.every((item)=>{
})
}
smallestCommons([1,5]);
My Question
I am asking a lot, so if you answer it is greatly appreciated!
Upvotes: 0
Views: 310
Reputation: 142
// since the number is evenly divided by all numbers from min to max
// it is the least common multiple of all numbers in the array [min, min + 1, min + 2, ... max]
const smallestCommonMultiple = (a, b) => {
const [min, max] = [Math.min(a, b), Math.max(a, b)];
// create the array from min to max
const range = [...Array(max - min + 1)].map((_, k) => min + k);
// greatest common divisor of two numbers
const gcd = (a, b) => b ? gcd(b, a % b) : Math.abs(a);
// least common multiple of two numbers
const lcm = (a, b) => a * b / gcd(a, b);
// least common multiple of an array of numbers
const lcma = array => array.reduce(lcm);
return lcma(range);
}
console.log(smallestCommonMultiple(1, 3));
console.log(smallestCommonMultiple(2, 4));
console.log(smallestCommonMultiple(3, 5));
Upvotes: 0