Tutorialspoint
Problem
Solution
Submissions

Sieve of Eratosthenes

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to implement the Sieve of Eratosthenes algorithm to find all prime numbers up to a given number `n`.

Example 1
  • Input: n = 10
  • Output: 2 3 5 7
  • Explanation:
    • Step 1: Create a boolean array of size n+1 initialized as true (assuming all numbers are prime initially).
    • Step 2: Mark 0 and 1 as non-prime (false).
    • Step 3: Starting from 2, iterate through each number. If it's marked as prime, mark all its multiples as non-prime.
    • Step 4: For n = 10, after sieving:
      • 2 is prime, mark 4, 6, 8, 10 as non-prime
      • 3 is prime, mark 6, 9 as non-prime
      • 4 is already marked as non-prime
      • 5 is prime, mark 10 as non-prime
    • Step 5: Return all numbers still marked as prime: 2, 3, 5, 7.
Example 2
  • Input: n = 20
  • Output: 2 3 5 7 11 13 17 19
  • Explanation:
    • Step 1: Create a boolean array of size n+1 initialized as true.
    • Step 2: Mark 0 and 1 as non-prime.
    • Step 3: Starting from 2, iterate through each number. If it's marked as prime, mark all its multiples as non-prime.
    • Step 4: For n = 20, after sieving:
      • 2 is prime, mark 4, 6, 8, 10, 12, 14, 16, 18, 20 as non-prime
      • 3 is prime, mark 6, 9, 12, 15, 18 as non-prime
      • 5 is prime, mark 10, 15, 20 as non-prime
      • 7 is prime, mark 14 as non-prime
    • Step 5: Return all numbers still marked as prime: 2, 3, 5, 7, 11, 13, 17, 19.
Constraints
  • 1 ≤ n ≤ 10^6
  • Time Complexity: O(n log log n)
  • Space Complexity: O(n)
ArraysAlgorithmsWalmartSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the Sieve of Eratosthenes algorithm to find all prime numbers up to `n`.
  • Create a boolean array to mark non-prime numbers.
  • Iterate through the array and mark multiples of each prime number as non-prime.
  • The remaining unmarked numbers are prime.

Steps to solve by this approach:

 Step 1: Create a boolean array of size n+1 and initialize all entries as true.

 Step 2: Mark 0 and 1 as non-prime (false).
 Step 3: Starting from 2, iterate through all numbers up to square root of n.
 Step 4: If the current number is marked prime, mark all its multiples as non-prime.
 Step 5: After completion, all numbers still marked true are prime.
 Step 6: Iterate through the array and output all prime numbers.

Submitted Code :