function Factors(remainder) {
var factors = [], i;
for (i = 2; i <= remainder; i++) {
while ((remainder % i) === 0) {
factors.push(i);
remainder /= i;
}
}
return factors;
}
Can we just use if
instead of while
?
function Factors(remainder) {
var factors = [], i;
for (i = 2; i <= remainder; i++) {
if(remainder%i===0) {
factors.push(i);
remainder /= i;
}
}
return factors;
}
3
Answers
The reason is because the function you with the
while
is looking for prime factors. Meanwhile, the function with anif
only finds a few factors which may or may not be primes. Let’s use the number 12. If you run the function with thewhile
, the resulting array should be [2,2,3], meanwhile, using theif
statement, you get [2,3]. The first answer is the correct one because 2 x 2 x 3 = 12 and every number in the array is a prime number, meanwhile 2 x 3 = 6.This snippet demonstrates the difference between using
while
and usingif
The
if
statement will only check if remainder is divisible byi
at that moment.The
while
loop will keep dividing remainder byi
as long as remainder% i === 0
(i.e.,remainder
is divisible byi
). It ensures that all factors ofi
are captured.