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

Below is a function that returns simple factors of a given number in JavaScript. I did not write this function, but studied it to expand my knowledge in programming.

My questions are about the while loop, which is inside the next if statement.

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

Questions

  • What is the purpose of the while loop if there is no code after it?
  • What happens when the while loop evaluates to true?
  • What happens when the while loop evaluates to false?

Here is the whole function.

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!!!

+3
source share
8 answers

It really does something like this:

if(num % x){

    x = 3;

    while(num % x){

        x = x + 2;

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

}

, x , . , x < root num % x . .

, , for

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

, for-loop, i >= n.

+2

x = x+2 while. 2 x , while true.

, while , . , . .

+2

, x 3, 2 x , root. , , x .

, x = x + 2 .

+2

:

                       V
while((num % x) && ((x = x+2) < root));

x = x + 2 - , , == ===, <<24 > .

(x = x + 2) < root x 2, root.

while if , .

+1

while x. :

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

x ( 2), root

0

while . , "x" , < root (/: && num% x < root).

, , // .

0

, , while . , , , .

Basically, the while loop will repeatedly check the state again and again. Yes, this can lead to an infinite loop if incorrectly encoded. In this case, "x" will increase by 2 until it reaches or exceeds the "root" value.

@Teemu credit for "reaches" or "

0
source

All Articles