Use Sieve of Eratosthenes to find prime numbers. - C++ Data Structure

C++ examples for Data Structure:Algorithm

Description

Use Sieve of Eratosthenes to find prime numbers.

Demo Code

#include <math.h>
#include <iostream>

void sieveOfEratosthenes(int[], int);

static const int limit = 1000;

int main(int argc, const char *argv[]) {
    int arrPrimes[limit + 1];

    for (int i = 0; i < limit; ++i) {
        arrPrimes[i] = 1;/*from  w  w  w  . j ava 2s .c  o  m*/
    }

    sieveOfEratosthenes(arrPrimes, limit);

    for (int i = 2; i < limit; ++i) {
        if (arrPrimes[i] == 1) std::cout << i << " ";
    }

    std::cout << std::endl;

    return 0;
}

void sieveOfEratosthenes(int arrPrimes[], int limit) {
    // outer loop only needs to loop to sqrt of limit
    for (int p = 2; p <= static_cast<int>(sqrt(limit)); ++p) {
        // if not changed then is prime
        if (arrPrimes[p] == 1) {
            // update all multiples of p starting at square of last found prime
            for (int i = p * p; i <= limit; i += p) {
                arrPrimes[i] = 0;
            }
        }
    }
}

Result


Related Tutorials