Skip to content

Instantly share code, notes, and snippets.

@VKen
Created November 25, 2019 17:02
Show Gist options
  • Save VKen/29b8499161e590504097beacec30e6df to your computer and use it in GitHub Desktop.
Save VKen/29b8499161e590504097beacec30e6df to your computer and use it in GitHub Desktop.
Get Lowest/Smallest Common Multiple From a Sequential Range of Numbers
/* get the lowest common multiple from a sequential range of numbers
expect arr = [a, b], where `a` and `b` are the (inclusive) edge range of natural numbers
*/
function smallestCommons(arr) {
let min = Math.min(...arr), max = Math.max(...arr),
numList = Array.from(Array(max - min +1).keys(), (val) => val + min),
factorMap = {};
numList.forEach((val) => { // generate the prime factors count mapping
for (let [key, value] of Object.entries(primeFactor(val))) {
if (!factorMap.hasOwnProperty(key)) factorMap[key] = value;
if (factorMap[key] < value) factorMap[key] = value;
}
})
return [...Object.entries(factorMap)].map(
(val) => { return Math.pow(parseInt(val[0]), val[1])}
).reduce((acc, val) => acc * val);
}
/* get the prime factors of any given natural number above 1, using Sieve of Eratosthenes */
function primeFactor(num) { // prime factorization
let factors = [];
// handle even prime number
while (num % 2 === 0) {
factors.push(2);
num /= 2;
}
if (num >= 3) { // starting from the smallest odd-number prime
// handle the odd prime numbers
Array.from(
Array(Math.ceil(Math.sqrt(num)) - 3 + 1).keys(),
(val) => val * 2 + 3
).forEach((val) => {
while (num % val == 0) {
factors.push(val);
num /= val;
}
});
// leftover number is prime
if (num > 2) factors.push(num);
}
// create a prime factors mapping `{prime_number[1]: index[1], ...prime_number[n]: index[n]}`
// where prime_num ^ index = factor of number
let primeFactorMap = {};
factors.forEach((val) => {
if (!primeFactorMap.hasOwnProperty(val.toString())) {
primeFactorMap[val.toString()] = 0
}
primeFactorMap[val.toString()] += 1;
})
return primeFactorMap;
}
console.log(smallestCommons([23, 18])); // Output: 6056820
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment