Java Reference
In-Depth Information
The outer loop is indexed by i and steps through the possible values that need to be checked for prime-
ness. The inner loop is indexed by j , the value of j being a trial divisor. This determines whether any
integer less than the value being tested for primality is an exact divisor.
The checking is done in the if statement in the inner loop. If j divides i exactly, i%j is 0, so isPrime
is set to false . In this case the break executes to exit the inner loop — there is no point in continuing
as you now know that the value being tested is not prime. The next statement to be executed is the if
statement after the closing brace of the inner loop block. You can also reach this point by a normal exit
from the loop that occurs when the value is prime so you need a way to determine whether the current
value of i was found to be prime or not. The isPrime variable solves this problem. You just check the
value of isPrime and if it has the value true , you have a prime to display so you execute the println()
call.
You could simplify this example if you used the labeled continue statement instead of the break state-
ment as in the next Try It Out.
TRY IT OUT: Calculating Primes II
Try the following changes to the code in the Primes class:
public class Primes2 {
public static void main(String[] args) {
int nValues = 50; // The maximum value to be
checked
// Check all values from 2 to nValues
OuterLoop:
for(int i = 2; i <= nValues; ++i) {
// Try dividing by all integers from 2 to i-1
for(int j = 2; j < i; ++j) {
if(i%j == 0) { // This is true if j divides
exactly
continue OuterLoop;
// so exit the loop
}
}
// We only get here if we have a prime
System.out.println(i);
// so output the value
}
}
}
Primes2.java
If you've keyed it in correctly, you get the same output as the previous example.
How It Works
Search WWH ::




Custom Search