ICS 211 Homework 3

Sieve of Eratosthenes

Write a program to compute and print all the prime numbers less than or equal to a given n. You do this by implementing the Sieve of Eratosthenes algorithm. The fundamental idea of this algorithm is simple: This is algorithm 1.

To work, the sieve must be initialized with all the numbers from 2 to n, inclusive. For example, if n is 10, the sieve must be initialized with 2, 3, 4, 5, 6, 7, 8, 9, and 10.

Then, 2 is a prime. Removing 2 (and printing it) and removing all the multiples of 2 gives: 3, 5, 7, 9, so 3 is a prime. Removing and printing 3, and removing all the multiples of 3 gives: 5, 7.

Repeating the operation will show that 5 and then 7 are also prime.

You must implement the algorithm by using an array of booleans, rather than an array of numbers:

Your array will have two more elements than needed, one each for 0 and 1. As long as you begin your loop at index 2, that is not a problem.

If you have trouble thinking in terms of true or false, you can think in terms of colors. A number that has never been visited before is blue. The first blue number is prime, so is colored green (all primes will be colored green). Any multiples of this number will be colored red (and set to false).

If you wish, you may stop the loop once you have reached an index i such that i * i > n. At that point, the values in the array (at indices > i) will never change. Then, you need is another loop to go through these elements, and print the indices for the values that are true. This is algorithm 2.

You only need to implement either algorithm 1 or algorithm 2. Both algorithms should give the same result. But whichever algorithm you implement, you must implement it using a boolean array as described above. Also, you must understand both algorithms, so that you can do the next part.

Sample outputs

When given argument 10, the program should print:
2
3
5
7

When given argument 11, the program should print:

2
3
5
7
11

When given argument 1 (or less) the program should print nothing.

When given a non-numeric argument, or the wrong number of arguments, the program should print an appropriate error message and exit.

Algorithm Analysis

Write up a runtime analysis of both algorithms 1 and 2, giving the big-O of each, and explaining how you got your results. Send your analysis to the TA together with your code. This part counts for 25% of the grade on this assignment.

Turning in the Assignment

Email your assignment to the TA following the instructions posted here.