 A Java Course Outline
Using the Java By Dissection book
by Ira Pohl and Charlie McDowell

Homework 6 -The Sieve of Erastophenes

We will write a program that will print a table of primes between 2 and n where `n` will be specified as input and read in using `tio`. The sieve uses a boolean array with each element set to true. The sieve method is to use a loop to strike out the multiples for each prime. The array elements that are left true are those that represent a prime. So, if

`sieve = sieve=sieve=sieve=sieve= … sieve = true`

Then starting at `sieve` skipping every other element changes this even-index elements to false. So after this loop all the elements divisible by 2 are set to false except for the prime `sieve`. Now do the same for elements` sieve `at intervals of 3. You do this upto `Math.sqrt(n)`. (You only need to go up to this point. Can you tell why?) When this striking out process is complete only the ```sieve[i] == true``` represents that `i` is prime. Print out the primes in a neat table.

Some ideas include

• Hand simulate the algorithm on something like 0 to 10. Then try and code as a method the filling of the sieve array to all true.
• Code the striking out method where an array is an argument and the interval and starting point of the strike out procedure are parameters.
• Finally code a method that prints out the results in an easily read manner.

What is new here is using arrays. Array variables are reference variables. Such variables, unlike native type variable, can have their values changed by a method. This is a critical idea you need to master.

Hints