CHAPTER 14

COLLECTION OF ACADEMIC PROGRAMS

14.1 Prime Numbers

Prime numbers are very important in mathematics as well as in computer science. There are many algorithms for finding prime numbers. Let us write programs based on two common algorithms.

14.1.1 Sieve of Eratosthenes

Sieve of Eratosthenes algorithm is taught in high school mathematics. This is a simple algorithm. It is not necessarily the most efficient. The idea behind it is very simple. Cross out (remove) all numbers which are multiples of any prime numbers. Naturally, all those numbers which remain intact are prime numbers.

The working procedure can be explained as follows.

First, draw a 10 by 10 grid and write numbers 1 to 100 in it (Figure 14.1). Next draw a square around 1, as ...

Get Programming with Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.