You are going to implement a class that computes all the primes up to some integer n. The technique you are to use was developed by a Greek named Eratosthenes who lived in the third century BC. The technique is known as the Sieve of Eratosthenes. The algorithm is described by the following pseudocode:
create a queue and fill it with the consecutive integers 2 through n inclusive.
create an empty queue to store primes.
do {
obtain the next prime p by removing the first value in the queue of numbers.
put p into the queue of primes.
go through the queue of numbers, eliminating numbers divisible by p.
} while (p < sqrt(n))
all remaining values in numbers queue are prime, so transfer them to primes queue
You are to use the Queue interface provided. When you want to construct a Queue object, you should make it of type LinkedQueue. These classes are included.
You should define a class called Sieve with the following public methods:
Sieve() - Constructs a sieve object.
void computeTo(int n) - This is the method that should implement the sieve algorithm. All prime computations must be implemented using this algorithm. The method should compute all primes up to and including n. It should throw an IllegalArgumentException if n is less than 2.
void reportResults() - This method should report the primes to System.out. It should throw an IllegalStateException if no legal call has been made yet on the computeTo method. It is okay for it to have an extra space at the end of each line.
int getMax() - This is a convenience method that will let the client find out the value of n that was used the last time computeTo was called. It should throw an IllegalStateException if no legal call has been made yet on the computeTo method.
int getCount() - This method should return the number of primes that were found on the last call on computeTo. It should throw an IllegalStateException if no legal call has been made yet on the computeTo method.
Your reportResults method should print the maximum n used and should then show a list of the primes, 12 per line with a space after each prime. Notice that there is no guarantee that the number of primes will be a multiple of 12. The calls on reportResults must exactly reproduce the format of the sample log. The final line of output that appears in the log reporting the percentage of primes is generated by the main program, not by the call on reportResults.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Laura Peterson wrote:Any reason why I am getting the number 3 twice?
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors