Write C++ code for Sieve of Eratosthenes
- User
Write C++ code for Sieve of Eratosthenes
- Assistant
Certainly! Below is a C++ implementation of the Sieve of Eratosthenes algorithm, which efficiently finds all prime numbers up to a given limit
N.cpp#include <iostream> #include <vector> #include <cmath> void sieve(int N, std::vector<bool>& is_prime) { // Initialize all entries as true. A value in is_prime[i] will // finally be false if i is Not a prime, else true. is_prime.assign(N + 1, true); // 0 and 1 are not prime numbers is_prime[0] = is_prime[1] = false; // Loop up to the square root of N int limit = std::sqrt(N); for (int i = 2; i <= limit; ++i) { if (is_prime[i]) { // Mark all multiples of i as non-prime for (int j = i * i; j <= N; j += i) is_prime[j] = false; } } } int main() { int N; std::cout << "Enter the limit N: "; std::cin >> N; // Vector to hold prime status of numbers std::vector<bool> is_prime; // Run the sieve algorithm sieve(N, is_prime); // Output the prime numbers std::cout << "Prime numbers up to " << N << " are:\n"; for (int i = 2; i <= N; ++i) { if (is_prime[i]) std::cout << i << " "; } std::cout << std::endl; return 0; }Explanation:
-
sieve function: This function initializes a boolean vector
is_primewhere each index represents a number up toN. Initially, all entries are set totrue(assuming all numbers are prime). Then, it iterates from2tosqrt(N)and marks the multiples of each prime number asfalse(not prime). -
Main function:
-