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:

    int main ()
    {

      // Create a sieve of ints, initially set to 1.
      const int sievesize = 100;
      std::vector<int, std::allocator<int> >
        sieve ((size_t)sievesize, 1);

      // At positions that are multiples of i, set value to zero.
      for (int i = 2; i * i < sievesize; i++)
        if (sieve[i])
          for (int j = i + i; j < sievesize; j += i)
            sieve[j] = 0;

      // Now output all the values that are still set.
      for (int j = 2; j < sievesize; j++)
        if (sieve[j])
          std::cout << j << " ";

      return 0;
    }