Smallest Common Multiple
I’m having trouble understanding one of their solution:
Solution 4 - Prime factorization (Click to Show/Hide)
// Find the SCM of a range of numbers
function smallestCommons(arr) {
let primeFactors = {};
const [min, max] = arr.sort((a, b) => a - b);
for (let i = min; i <= max; i++) {
// Factorize number in range
let primes = getPrimeFactors(i);
for (let j in primes) {
// Add factor to set or update number of occurrences
if (!primeFactors[j] || primes[j] > primeFactors[j]) {
primeFactors[j] = primes[j]
}
}
}
// Build SCM from factorization
let multiple = 1;
for (let i in primeFactors) {
multiple *= i ** primeFactors[i]
}
return multiple;
}
// Compute prime factors of a number
function getPrimeFactors(num) {
const factors = {};
for (let prime = 2; prime <= num; prime++) {
// Count occurances of factor
// Note that composite values will not divide num
while ((num % prime) === 0) {
factors[prime] = (factors[prime]) ? factors[prime] + 1 : 1;
num /= prime;
}
}
return factors;
}
smallestCommons([1, 5]);
Specifically, the ternary operator inside the while
loop in getPrimeFactors
function:
while ((num % prime) === 0) {
factors[prime] = (factors[prime]) ? factors[prime] + 1 : 1; // confused
num /= prime;
}
For example if I pass in getPrimeFactors(20)
, I get out an object { 2: 2, 5: 1 }
.
This is me trying to understand it by rewriting in conventional if-else statement:
while (num % prime === 0) {
if (factors[prime]) {
factors[prime] = factors[prime] + 1;
} else factors[prime] = 1;
num /= prime;
}
So what they’re trying to do is:
- If the object
factors
doesn’t have propertyprime
(prime is2
):- Create a new prop with value
1
(1
being occurence count). - Then
num /= prime
will make change num from20
to10
for the next loop.
- Create a new prop with value
- Next loop, because now
factors
does have property{ 2: 1 }
- The condition
if (factors[prime])
istrue
, - we increase the occurence count, hence
{ 2: 1 }
becomes{ 2: 2 }
.
- The condition
- We repeat this until
num % prime != 0
(num is5
now) and end the while loop.
I can’t help but feel like I’m missing something. Any insight is appreciated.
I was actually able to pass the challenge without looking up solutions, using the same approach. Then I found this solution and the code is like 3 times shorter so I’m scratching my head trying to understand it.