Write a method that takes a single int argument and returns
an array of that many ints where each element in the array
has as its value the index where it occurs.
Write a method that takes an array of ints and returns a count of the number of elements in the array whose value is not zero.
Write a method that takes two arguments, an array of ints and a positive int, and sets all the elements of the array at indexes that are proper multiples of the number given to zero. (Proper multiples of a number n are n times any whole number greater than 1.) For instance, the first proper multiple of 2 is 2 times 2 or 4, so if the second argument is 2, you should set all the elements in the array at even indexes starting at 4 to zero.
Write a method that takes an array of ints and returns a new array containing only the non-zero values in the argument array.
Write a method that takes an array of ints and an int representing an index into the array. It should return the next non-zero value in the array at an index greater than the one given by the second argument. For instance given the array { 0, 0, 10, 7, 0, 13 } and the starting position 3, it should return 13. If there are no non-zero values after the given starting point, return 0.
For the culmination of this week’s Boot ups, write a method that takes an
int argument and returns an int array contaning
all the prime numbers less than that number. You can do this by
implementing
the Sieve of
Eratosthenes using the methods written earlier in this series.
The procedure of the Sieve of Eratosthenes is somethning you could do on
paper: make a list of all the whole numbers less than n. Then
cross out 0 and 1. Then circle the first
uncrossed out number (which will be 2 the first time) and
cross out all the proper multiples of the number you just circled. Then
repeat, circling the next uncrossed out, uncircled number (3
will be next) and crossing out all its proper multiples. Continue until
all the numbers are either circled or crossed out. Then copy all the
circled numbers to a fresh piece of paper; that is your list of primes
less than n.
In your implementation, you will "cross out" numbers by setting their spot
in the array to 0. All of the methods you’ve written as part
of this series will be used in your final implementation
though countNonZeros will only be used indirectly, since you
should have used it to implement nonZeros.
When you are done, look at the Wikipedia article about the Sieve which
suggests an optimization that you could make via a change
to clearMultiples. If you have time, try to implement it.
It’s described in the paragraph in the Overview section that starts, “As a
refinement”. The change you will need to make make would be
in clearMultiples. Instead make a new
method fastClearMultiples that implements the change and then
change your primes method to use it instead
of clearMultiples.
This boot up will build up over the course of a week, one method per day.