changeset 9:8f82abf1b732

Sieve of Eratosthenes in C++
author Eris Caffee <discordia@eldalin.com>
date Wed, 03 Jun 2015 16:02:31 -0500
parents 707cbc379d26
children a4b0df828667
files sieve_of_eratosthenes/sieve.cpp
diffstat 1 files changed, 42 insertions(+), 0 deletions(-) [+]
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/sieve_of_eratosthenes/sieve.cpp	Wed Jun 03 16:02:31 2015 -0500
     1.3 @@ -0,0 +1,42 @@
     1.4 +#include <iostream>
     1.5 +#include <vector>
     1.6 +#include <cmath>
     1.7 +#include <sstream>
     1.8 +
     1.9 +void sieve( int limit, std::vector<int> &primes ) {
    1.10 +    std::vector<int> nums;
    1.11 +    for ( int i = 0; i <= limit; ++i )
    1.12 +        nums.push_back(1);
    1.13 +    nums[0] = nums[1] = 0;
    1.14 +
    1.15 +
    1.16 +    float sq = sqrt(limit);
    1.17 +    for ( int i = 2; i <= sq; ++i ) {
    1.18 +        if ( nums[i] != 0 ) {
    1.19 +            for ( int j = i*i; j <= limit; j += i )
    1.20 +                nums[j] = 0;
    1.21 +            }
    1.22 +        }
    1.23 +
    1.24 +    for ( int i = 2; i <= limit; ++i )
    1.25 +        if ( nums[i] != 0 )
    1.26 +            primes.push_back( i );
    1.27 +
    1.28 +    }
    1.29 +
    1.30 +
    1.31 +
    1.32 +int main( int argc, char **argv ) {
    1.33 +    int limit;
    1.34 +
    1.35 +    std::stringstream ss(argv[1]);
    1.36 +    ss >> limit;
    1.37 +
    1.38 +    std::vector<int> primes;
    1.39 +
    1.40 +    sieve( limit, primes );
    1.41 +
    1.42 +    for ( int i=0; i < primes.size(); ++i )
    1.43 +        std::cout << primes[i] << std::endl;
    1.44 +
    1.45 +    }