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[0] = sieve[1]=sieve[2]=sieve[3]=sieve[4]= … sieve[100] = true`

Then starting at `sieve[4]` 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[2]`. Now do the same for elements` sieve[6] `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

• Write out your pseudocode
• Step through line by line in your pseudocode
• Keep track of all variables in your array and verify to yourself that this will give a valid answer
• Start to code

If you don't understand how this will work, don't sit down and start banging out code. That path leads to insanity! So, first, sit down and figure out what the problem is asking. Next, write pseudocode to match what Prof Pohl has given. Then step through it on your own. Finally, when you understand the algorithm, start to code.

Feel free to report any site problems to the Webmaster, Debra Dolsberry.