Reputation: 385
I'm always assumed that if a statement was declared false, such as boolean valid = false
, then writing !valid
would in turn reverse valid
to be true. Yet, was this an entirely wrong misconception? For instance, in the code below;
for (int check=3; check <= primeLimit; check += 2) {
boolean divisorFound=false;
for (int div=3; div<=Math.sqrt(check) && !divisorFound; div += 2) {
if (check%div==0)
divisorFound=true;
}
Is the second for loop searching for divisorFound
to be true of false?
Because if it was implying that the divisor is false, wouldn't it just say :
div<=Math.sqrt(check) && divisorFound;
Upvotes: 0
Views: 115
Reputation: 10810
The second loop is saying to continue looping when div
is less than Math.sqrt(check)
and no divisor has been found. When divisorFound
has been set to true, then the inner loop will fail its condition.
I think you must have misread the code as this is a pretty straight forward boolean condition.
Upvotes: 1
Reputation: 567
I'm assuming you didn't write this code and are trying to understand what it's purpose is. The inner loop should continue until a divisor is found. So it repeatedly checks to see if !divisorFound
evaluates to true
. In other words, "has a divisor not been found yet?".
Once a divisor is found, divisorFound
is set to true
and the expression !divisorFound
evaluates to false
, so the loop will stop.
If the condition check that you suggested was used:
div<=Math.sqrt(check) && divisorFound
The loop body would never be reached. divisorFound
is false
to start with so the continue condition would immediately fail and the loop would terminate.
Upvotes: 5