Skip to content

Instantly share code, notes, and snippets.

@taesup
Created July 25, 2019 07:49
Show Gist options
  • Save taesup/ddc19f6db4db1022bc3b1e4a073f21ff to your computer and use it in GitHub Desktop.
Save taesup/ddc19f6db4db1022bc3b1e4a073f21ff to your computer and use it in GitHub Desktop.
Given a set of factors, find the smallest number where all the factors evenly divide into the number
console.time('test');
function smallestMultiple(num) {
if (num === 1) {
return 1;
}
// generate factors from 4 to num
let factors = {};
for (let i = 2; i <= num; i++) {
// factorization
const factorized = factorize(i);
Object.entries(factorized).forEach((factor) => {
if (!factors[factor[0]] || factor[1] > factors[factor[0]]) {
factors[factor[0]] = factor[1];
}
});
}
// multiple all slimfactors to find smallest multiple
return Object.entries(factors).reduce((p, c) => {
return p * Math.pow(parseInt(c[0]), c[1]);
}, 1);
}
function factorize(num) {
let factors = {};
for (let i = 2; i <= num; i++) {
while (num % i === 0) {
if (factors[i]) {
factors[i]++;
} else {
factors[i] = 1;
}
num = num / i;
}
}
factors[num] = 1;
return factors;
}
console.log(smallestMultiple(20));
console.timeEnd('test');
module.exports = smallestMultiple;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment