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’ insted 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;
}
Amir Mohammadzadeh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5
This snippet demonstrates the difference between using while
and using if
function FactorsWhile(remainder) {
var factors = [], i;
for (i = 2; i <= remainder; i++) {
while ((remainder % i) === 0) {
factors.push(i);
remainder /= i;
}
}
return factors;
}
function FactorsIf(remainder) {
var factors = [], i;
for (i = 2; i <= remainder; i++) {
if ((remainder % i) === 0) {
factors.push(i);
remainder /= i;
}
}
return factors;
}
console.log("Using WHILE: " + JSON.stringify(FactorsWhile(4)));
console.log("Using IF: " + JSON.stringify(FactorsIf(4)));
The reason is because the function you with the while
is looking for prime factors. Meanwhile, the function with an if
only finds a few factors which may or may not be primes. Let’s use the number 12. If you run the function with the while
, the resulting array should be [2,2,3], meanwhile, using the if
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.
The if
statement will only check if remainder is divisible by i
at that moment.
The while
loop will keep dividing remainder by i
as long as remainder % i === 0
(i.e., remainder
is divisible by i
). It ensures that all factors of i
are captured.