My question is related to the following code:
public static void main(String[] args) { // Find Prime Numbers from 0 to 100 int i; for (i=2; i <= 100; i++) { int j = 2; boolean iPrime = true; //The following line gives incorrect results, but should execute faster // while ((iPrime = true) && (j < (i / 2 + 1))) { //The following line gives correct results but performs un-necessary operations //by continuing to calculate after the number is found to be "not prime" while (j < (i / 2 + 1)) { j++; if ((i % j) == 0) { iPrime = false; //System.out.println(j + " is a factor of " + i); } } if (iPrime) { System.out.println(i + " is a prime number!"); } } }
Now that I have commented on the code, I am trying to get my program to run faster by executing the while loop only when iPrime = true. 50% of the numbers are divisible by 2, and therefore, after this is established, the calculations may stop.
I am doing this project as part of a beginnerβs example from a book, Iβm actually trying to calculate up to 1,000,000 as quickly as possible just for my own βextra credit" ...
I read that the "short circuit" and the "operator" && only evaluate the second half of the operator, if the first half is true, if it is false, the two are not evaluated against each other (CPU saving)
And it will also exit the cycle, which will save even more CPU ...
But for some reason it is not working properly! I put in more system instructions to System.out.println (), indicating what "iPrime" is, and stranget is displayed ... It turns iPrime on and off and evaluates every number that I cannot understand.
source share