What is the functionality of the while loop inside the if statement? JavaScript
javascript, while-loop
Solution
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`.
Problem
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 - What is the purpose of a while loop if there is no code after it? - What is happening when the while loop evaluates true? - 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!!!