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, as I've commented in the code, what I'm trying to achieve is a faster execution of my program by executing the 'while' loop only when iPrime = true. 50% of numbers are divisible by 2 and so this once this has been established the calculations can stop.
I'm doing this project as part of a beginners 'example' from a book, I actually am trying to calculate up to 1000000 as quickly as possible just for my own "extra credit"...
I read that the "short circuit 'and' operator" && only evaluates the second half of the statement if the first half is true, if it is false, the two are not evaluated against each other (saving CPU)
And it will also exit the loop, which will save even more CPU...
But for some reason, it is not working correctly! I've put more System.out.println() statements throughout, listing what 'iPrime' is - and the output is stranget... It switches iPrime on and off and evaluates every number, which I cannot understand.