Tutorialspoint
Problem
Solution
Submissions

Count Primes

Certification: Intermediate Level Accuracy: 25% Submissions: 4 Points: 10

Write a C# program to count the number of prime numbers less than a non-negative number n. Implement an optimized solution to efficiently calculate this count for large values of n.

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
  • The solution should handle large values of n efficiently
  • Time Complexity: O(n log log n)
  • Space Complexity: O(n)
ArraysNumberIBMApple
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 for an efficient solution
  • Initialize an array to track which numbers are prime
  • Start with marking all numbers as potential primes
  • Iterate through numbers starting from 2, and mark all multiples as non-prime
  • Only check numbers up to the square root of n for optimization

Steps to solve by this approach:

 Step 1: Handle edge cases - if n is less than or equal to 2, return 0 (there are no primes less than 2).

 Step 2: Create a boolean array of size n to mark which numbers are prime.
 Step 3: Initially, mark all numbers from 2 to n-1 as potential primes (true in the array).
 Step 4: Implement the Sieve of Eratosthenes algorithm - start from the smallest prime (2).
 Step 5: For each prime number, mark all its multiples as non-prime (false in the array).
 Step 6: Optimize by only checking numbers up to the square root of n, as larger factors would have been marked by smaller factors.
 Step 7: Count all remaining numbers marked as prime (true in the array) and return the count.

Submitted Code :