Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the functionality of the while loop inside the if statement? JavaScript

Below is a function that returns the prime factors of a given number in JavaScript. I did not write the function but have been studying it to extend my programming knowledge.

My questions are about the while loop that is inside the following if statement.

if(num % x){
    x = 3; 
    while((num % x) && ((x = x+2) < root));
}

Questions

  1. What is the purpose of a while loop if there is no code after it?
  2. What is happening when the while loop evaluates true?
  3. What is happening when the while loop evaluates false?

Here is the function in it's entirety.

function getPrimeFactors(num){
    num = Math.floor(num);
    var root = 0;
    var factors = [];
    var doLoop = 1 < num;
    var x = 0;

    while(doLoop){
        root = Math.sqrt(num);
        x = 2;

        if(num % x){
            x = 3;
            while((num % x) && ((x = x+2) < root));
        }

        if(x > root){
            x = num;
        }else{
            x = x;
        }

        factors.push(x);

        doLoop = (x != num);

        num = num/x;
    }

    return factors;
}

Thanks for the help!!!

like image 770
JaredRogers Avatar asked Dec 08 '25 22:12

JaredRogers


1 Answers

It is really doing something like this:

if(num % x){

    x = 3;

    while(num % x){

        x = x + 2;

        if(x < root)
            continue;
        else
            break;
    }

}

Except, two is added to x right in the conditional, so there is no need for a body. The loop will execute until x < root or num % x fails to be true. The body just doesn't have any instructions in it.

Its very similar to what happens when you execute a for loop

for(int i=0; i < n; i++)
    ;

See there are no instructions in the for-loop body, but the loop will still add one to i until i >= n.

like image 156
Joel Avatar answered Dec 11 '25 10:12

Joel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!