Java Reference

In-Depth Information

for using this code, we change the program segment to set a boolean variable

depending on whether
i
is prime and then use this task before the test and change

the test accordingly:

// Set x to the number of primes in 2..99

int
x= 0;

// {
invariant:
x =
the number of primes in
2..i-1 }

for
(
int
i= 2; i != 100; i= i + 1) {

Set fresh variable
b
to
"i
is prime
";

if
(b) { x= x + 1; }

See lesson

page 7.6 to

obtain the final

program

}

Implementing the assignment to b

We now implement the statement
b = "i
is prime
"
, using the code from

Fig. 7.4, with slight adjustments. With this preparation, we can now move this

code into the program. The result appears in Fig. 7.6. This completes the devel-

opment of the program to compute the number of primes in
2..99
.

How to read Fig. 7.6

When reading the program segment of Fig. 7.6 for the first time, try to un-

derstand the outer loop. In doing so, view its repetend as a sequence of two state-

ments:

Activity

7.6-2

Set fresh variable
b
to
"i
is prime
";

if
(b) { x= x + 1; }

//
Set
x
to the number of primes in
2..99

int
x= 0;

// {
invariant:
x=
the number of primes in
2..i-1 }

for
(
int
i= 2; i != 100; i= i + 1) {

//
Set fresh variable
b
to
"i
is prime
";

boolean
b= i > 1;

int
k= 2;

// {
invariant:
b==i>1and
no integer in
2..k-1
divides
i }

while
(b && k != i) {

if
(i % k == 0) { b=
false
; }

k= k + 1;

}

if
(b) { x= x + 1; }

}

Figure 7.6:

Computing the number of primes in
2..99

Search WWH ::

Custom Search