Amir Mohammadzadeh
Amir Mohammadzadeh

Reputation: 1

Why divide by the same factor in a loop in factorization?

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;
}

Upvotes: -1

Views: 75

Answers (3)

Ghost
Ghost

Reputation: 5019

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.

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35031

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)));

Upvotes: 1

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.

Upvotes: 0

Related Questions