Getting started

Start a new Clojure project in Eclipse using New → Project → Clojure → Clojure Project. Name the new project lab10.

Open the file src/lab10/core.clj. Create your functions in this file. When you are ready to test your functions, start a REPL by right-clicking in the editor and choosing Clojure → Load file in REPL. When you modify your code, do the same thing to reload your definitions in the REPL.

If you would prefer to use Light Table, or edit your code in a text editor and run the Clojure REPL from the command line, feel free.

Your task

Complete the exercises shown below.

Start with the following function definition (from Lecture 13):

(defn make-is-multiple-of [n]
  (fn [x]
    (= (mod x n) 0)))

apply-sieve

Write a function called apply-sieve. It takes a sequence of integers whose first member is a prime number. It should return a sequence in which every multiple of that prime number (including itself) is removed.

Example call:

=> (apply-sieve [2 3 4 5 6 7 8 9 10 11 12 13 14 15])
(3 5 7 9 11 13 15)

Hints/requirements:

find-primes

Write a function called find-primes that computes a sequence containing all of the prime numbers up to a specified maximum integer. Example call:

=> (find-primes 40)
(2 3 5 7 11 13 17 19 23 29 31 37)

The basic idea is that you can use the apply-sieve function repeatedly to discover all of the prime numbers: if applied repeatedly starting with a list whose first element is a prime number, it is guaranteed to return a list whose first element is the next prime number. You can continue applying it until the first element is greater than or equal to the square root of the maximum integer.

This algorithm is called the Sieve of Eratosthenes.

Hints/specifications:

Initially I felt that there should be an elegant way to do this computation using reduce, although having thought about it a bit, I don't think there is. (However, I would be very happy to be proven wrong!)