C++ Online Compiler
Example: Sieve of Eratosthenes Prime Finder in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sieve of Eratosthenes Prime Finder #include <iostream> #include <vector> // Required for std::vector // Function to implement the Sieve of Eratosthenes void sieveOfEratosthenes(int upperBound, std::vector<bool>& isPrime) { // Step 1: Initialize all entries as true. A value in isPrime[i] will be false if i is not prime, else true. isPrime.assign(upperBound + 1, true); // Resize and fill with true isPrime[0] = false; // 0 is not prime isPrime[1] = false; // 1 is not prime // Step 2: Start from the first prime number, 2 for (int p = 2; p * p <= upperBound; ++p) { // If isPrime[p] is still true, then it is a prime if (isPrime[p] == true) { // Mark all multiples of p as not prime // Start from p*p because smaller multiples (p*2, p*3, etc.) would have already been marked // by smaller prime factors (2, 3, etc.) for (int i = p * p; i <= upperBound; i += p) isPrime[i] = false; } } } int main() { // Step 1: Define the range int lowerBound = 10; int upperBound = 30; // Step 2: Declare a boolean vector to store primality information // Its size will be upperBound + 1 to accommodate numbers from 0 to upperBound std::vector<bool> isPrime; // Step 3: Run the Sieve to populate the isPrime vector up to upperBound sieveOfEratosthenes(upperBound, isPrime); std::cout << "Prime numbers in range [" << lowerBound << ", " << upperBound << "] (Sieve):" << std::endl; // Step 4: Iterate through the specified range and print primes based on the Sieve result // Ensure lowerBound is at least 0. If it's less, adjust to 0 for vector access. int start = (lowerBound < 0) ? 0 : lowerBound; if (start > upperBound) { std::cout << "Invalid range." << std::endl; return 0; } for (int i = start; i <= upperBound; ++i) { if (isPrime[i]) { std::cout << i << " "; } } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS