Skip to content

Instantly share code, notes, and snippets.

@danialgoodwin
Created June 15, 2013 20:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danialgoodwin/5789439 to your computer and use it in GitHub Desktop.
Save danialgoodwin/5789439 to your computer and use it in GitHub Desktop.
Get prime numbers using the Sieve of Eratosthenes. Also, finds the sum of all the primes below one million. Used for Project Euler.
// Finds the sum of all the primes below one million.
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
const int NUM = 1000000;
int count = 1;
bitset<NUM> Sieve;
__int64 sum = 0;
Sieve.flip(); // Sets all bits to 1.
Sieve[0].flip(); // Sets 0 to not prime.
Sieve[1].flip(); // Sets 1 to not prime.
// Check all numbers from 2 to sqrt(NUM).
for (long i = 2; i * i < NUM; ++i)
{
if (!Sieve[i]) // If marked not prime.
{
continue;
}
else // If marked prime, set all multiples as not prime.
{
for (long j = 2 * i; j < NUM; j += i)
{
Sieve[j] = 0;
}
}
}
// Add together all primes less than NUM.
for (long i = 2; i < NUM; ++i)
{
if (Sieve[i])
{
count++;
sum += i;
}
}
cout << "Number of primes: " << count << endl;
cout << "The sum is: " << sum << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment