Tutorialspoint
Problem
Solution
Submissions

Count Primes less than n

Certification: Basic Level Accuracy: 40% Submissions: 5 Points: 5

Write a Java program to count the number of prime numbers less than a given non-negative integer n. A prime number is a natural number greater than 1 that is not divisible by any positive integer other than 1 and itself.

Example 1
  • Input: n = 10
  • Output: 4
  • Explanation:
    • Prime numbers less than 10 are 2, 3, 5, and 7.
    • There are 4 prime numbers less than 10.
    • Therefore, the output is 4.
Example 2
  • Input: n = 20
  • Output: 8
  • Explanation:
    • Prime numbers less than 20 are 2, 3, 5, 7, 11, 13, 17, and 19.
    • There are 8 prime numbers less than 20.
    • Therefore, the output is 8.
Constraints
  • 0 ≤ n ≤ 5 * 10^6
  • The solution should be efficient for large values of n
  • Time Complexity: O(n log log n)
  • Space Complexity: O(n)
NumberEYWalmart
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 efficiently find all prime numbers up to n
  • Create a boolean array to mark non-prime numbers
  • Initialize all numbers as prime (false in the array)
  • Starting from 2, iterate and mark all multiples of each prime number as non-prime
  • Count the numbers that remain marked as prime

Steps to solve by this approach:

 Step 1: Check if n ≤ 2. If true, return 0 (no primes).

 Step 2: Create a boolean array of size n and initialize all entries as true.
 Step 3: Start with the smallest prime number, 2, and iterate up to the square root of n.
 Step 4: For each prime number i, mark all its multiples starting from i² as non-prime.
 Step 5: Count all the numbers that remain marked as prime.
 Step 6: Return the count as the answer.
 Step 7: Output: 4 for n=10 and 8 for n=20.

Submitted Code :