Tutorialspoint
Problem
Solution
Submissions

Count primes

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

Write a C# program to count the number of prime numbers less than a non-negative integer n using the Sieve of Eratosthenes algorithm.

Example 1
  • Input: n = 10
  • Output: 4
  • Explanation:
    • There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2
  • Input: n = 0
  • Output: 0
  • Explanation:
    • There are no prime numbers less than 0.
Constraints
  • 0 ≤ n ≤ 5 * 10^6
  • Your solution must implement the Sieve of Eratosthenes algorithm
  • Time Complexity: O(n log log n)
  • Space Complexity: O(n)
ArraysPwCPhillips
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

  • Create a boolean array to mark non-prime numbers
  • Initially assume all numbers are prime
  • Starting from 2, mark all its multiples as non-prime
  • Continue this process for all unmarked numbers up to sqrt(n)
  • Count all unmarked numbers, which are prime

Steps to solve by this approach:

 Step 1: Handle edge cases: if n <= 2, return 0 (no primes less than 2).
 Step 2: Create a boolean array to mark composite (non-prime) numbers.
 Step 3: Initialize all numbers as potentially prime (false in our array).
 Step 4: Starting from 2, iterate up to the square root of n.
 Step 5: For each unmarked number, mark all its multiples (starting from its square) as composite.
 Step 6: Count all numbers that remain unmarked (these are the prime numbers).
 Step 7: Return the count of prime numbers.

Submitted Code :