[ Back to the overview Matrix ]

Test case : Prime Numbers

Write an application that prints the first 1000 prime numbers, in ascending order.
Due to the differences between imperative and functional languages, Marcin had to provide me with an detailed explanation :-)

A prime number is either 2, or an odd number not divisible by any prime number whose square is less than or equal the tested number.

Modularization: The program should consist of two parts, not counting possible generic auxiliary functions or classes. One part produces an object which wraps the knowledge about computing prime numbers in ascending order. The object must be able to compute as many prime numbers as someone will request, one by one, without prior declaration about how many of them will be requested, and without wasting time for computation of numbers which were not requested. It should not care how the numbers it computes will be used.

The other part takes an object which describes a sequence of integers and displays its first 1000 elements. It must not be tightly integrated with the previous part - it should be possible to substitute a different source of numbers by changing only one place.

The protocol of communication of requests for more numbers and for the numbers themselves should not rely on the fact that there exists only a single source of numbers in the whole program, i.e. the source of numbers should be encapsulated in an object which could be stored in a variable. The example is too small to get real benefit from that, but it should be clear that a better design is when the source of data can be explicitly passed as an object instead of being forced to be hardwired in the code which uses it.

Moreover, the sequence of numbers should be examinable multiple times concurrently. Each consumer sees the same sequence of numbers, and they are all taken from a shared source instead of being recomputed for each consumer from scratch. In other words, a request for a next prime should compute it using divisions only when nobody has requested so large number from this source before.


What is tested: lazy lists, recursive definition of a non-function

Contributed by Marcin 'Qrczak' Kowalczyk, qrczak at knm.org.pl