Last active
December 14, 2015 02:29
-
-
Save HelixSpiral/5013814 to your computer and use it in GitHub Desktop.
First time using std::vector<bool>. Decided to make a Sieve of Eratosthenes for practice. Takes a number for input and finds all the primes up to that number. Sieve[x] will return true if x is prime, false if not.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> // Needed for std::cin/cout | |
#include <vector> // Needed for std::vector | |
#include <cmath> // Needed for sqrt and ceil | |
int main() | |
{ | |
/* Will be the sieve */ | |
std::vector<bool> Sieve; | |
unsigned int x, y, limit; | |
std::cout << "Enter the number to stop at: "; | |
std::cin >> x; | |
/* Resize the sieve to the size we input, we use x+1 | |
because vectors start counting at 0, and since | |
we don't use 0 the actual number we need is 1 | |
higher than the vector. */ | |
Sieve.resize(x+1, true); | |
/* We only have to check numbers under the square root of the number | |
we're going to, any number higher than that, that isn't a | |
multiple of a previous number will be prime. */ | |
limit = ceil(sqrt(x)); | |
/* Loop for every number up to limit */ | |
for (x = 2; x < limit; ++x) | |
/* If this is true then we found a prime number */ | |
if (Sieve[x] == true) | |
/* Loop the multiples of the prime found up to | |
Sieve.size() and set to false */ | |
for (y = x*2; y < Sieve.size(); y += x) | |
Sieve[y] = false; | |
/* Print the primes found. */ | |
for (x = 1; x < Sieve.size(); ++x) | |
if (Sieve[x] == true) | |
std::cout << "Prime: " << x << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment