Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library User's Guide

5.4 Example Program: The Sieve of Eratosthenes

An example program that illustrates the use of vectors is the classic algorithm called the sieve of Eratosthenes, used to discover prime numbers.


NOTE -- Source code for this program is in the file sieve.cpp.

In the sieve of Eratosthenes, a list of all the numbers up to some bound is represented by an integer vector. The basic idea is to strike out (set to zero) all values that cannot be primes; thus all the remaining values are prime numbers. To do this, a loop examines each value in turn; for those that are set to one and thus not yet excluded from the set of candidate primes, it strikes out all multiples of the number. When the outermost loop is finished, all remaining prime values have been discovered. Here is the program:



Previous fileTop of DocumentContentsIndex pageNext file