
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)
Editorial
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. |
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