You bought a big box of random computer parts at a garage sale. You've started putting the parts together to build custom computers.
You want to test the performance of different combinations of parts, and decide to create your own benchmarking program to see how your computers compare. You choose the famous "Sieve of Eratosthenes" algorithm, an ancient algorithm, but one that should push your computers to the limits.
Your task is to create a program that implements the Sieve of Eratosthenes algorithm to find all prime numbers less than or equal to a given number.
A prime number is a number larger than 1 that is only divisible by 1 and itself. For example, 2, 3, 5, 7, 11, and 13 are prime numbers. By contrast, 6 is not a prime number as it not only divisible by 1 and itself, but also by 2 and 3.
To use the Sieve of Eratosthenes, you first create a list of all the numbers between 2 and your given number. Then you repeat the following steps:
You keep repeating these steps until you've gone through every number in your list. At the end, all the unmarked numbers are prime.
The tests don't check that you've implemented the algorithm, only that you've come up with the correct list of primes. To check you are implementing the Sieve correctly, a good first test is to check that you do not use division or remainder operations.
Let's say you're finding the primes less than or equal to 10.
You've examined all numbers and found 2, 3, 5, and 7 are still unmarked, which means they're the primes less than or equal to 10.
Simply type make chez
if you're using ChezScheme or make guile
if you're using GNU Guile.
Sometimes the name for the scheme binary on your system will differ from the defaults.
When this is the case, you'll need to tell make by running make chez chez=your-chez-binary
or make guile guile=your-guile-binary
.
(load "test.scm")
at the repl prompt.sieve.scm
reloading as you go.(test)
to check your solution.If some of the test cases fail, you should see the failing input and the expected output.
The failing input is presented as a list because the tests call your solution by (apply sieve input-list)
.
To learn more about apply
see The Scheme Programming Language -- Chapter 5
Sign up to Exercism to learn and master Scheme with 39 exercises, and real human mentoring, all for free.
We explore various approaches to the Sieve of Eratosthenes, starting with nested loops and lazy evaluation, then moving onto sets and finally looking at recursion.