skip to Main Content
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


  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.

    Login or Signup to reply.
  2. 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)));
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search