The code I wrote times out at a higher range. Any way to optimize the code by just using higher-order ES6 functions.
The link to the online environment: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple
function smallestCommons(arr) {
// Return the Smallest Common Multiple for pair of Input Numbers.
const [min, max] = arr.sort((a,b)=>a-b);
// Sorting Input Array to give min and max values for the range
const range = Array(max-min 1).fill(0).map((_,i)=>i min);
// Initialize the Array
let prodAll = range.reduce((product,number)=>product*number);
// Finding the product of all numbers which is a gauranteed multiple of the range
let res = Array(prodAll/max).fill(0).map((_,i)=>(i 1)*max) // Initialize an Array of all the multiples of the 'max' number upto 'prodAll'
.find(mulp=>range.every((val)=>mulp%val===0)); // check if any number meets the divisiblable criteria sooner then 'prodAll'
return res;
}
console.log(
smallestCommons([1,13])
)
CodePudding user response:
Try this:
function smallestCommons(arr) {
// Return the Smallest Common Multiple for pair of Input Numbers.
const [min, max] = arr.sort((a,b)=>a-b);
// Sorting Input Array to give min and max values for the range
const range = Array(max-min 1).fill(0).map((_,i)=>i min);
// Initialize the Array
let res = range.reduce((lcm, number) => {
// Calculate the least common multiple using the current value and the previously calculated lcm
return (lcm * number) / gcd(lcm, number);
}, max);
return res;
}
function gcd(a, b) {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}
smallestCommons([1, 4]);
This version uses the reduce
function to iterate through the range and calculate the least common multiple using the current value and the previously calculated lcm. It also uses separated function (gcd
) to calculate the greatest common divisor using Euclid's algorithm, which is more efficient.