CS 121: Assignment 1
Review of CS 120
Due: Monday, January 14, 10:00 am
Write a program that calculates all prime numbers less than 10,000. The program works as follows:
- Create a main method, and a method called ArrayList< Integer > sieve( int n ), which returns a list with
all the prime numbers less than n. The main method calls sieve( 10,000 ), and
prints out the results.
- Inside of sieve(), do the following:
- Call method createTrueArray( n ) to create a boolean array of size n.
- Set cells 0 and 1 of the array to false. Each cell in the array represents a number,
the boolean value represents whether it is prime or not. We start by assuming that all numbers greater
or equal 2 are prime, and then we remove the ones that are not.
- Loop over the array, starting at index 2.
- First, remove all multiples of 2, by setting the values for 4, 6, 8, ... to false.
- Then, look for the next number still marked true (in this case 3), and set all its multiples to false.
- Repeat with all numbers that are marked true. When you are done, only prime numbers will
be marked true.
- Call method booleanArrayToIntList() to return a list of integers that contains the primes.
- Method boolean[] createTrueArray( int n ) creates a boolean array of size n and initializes all its values to true.
- Method ArrayList< Integer > booleanArrayToIntList( boolean[] booleans ) loops through booleans,
and for each true value, it adds the corresponding number to a list. Finally, it returns the list.
CS 121