Count Primes
1 approach, code in every language
Problem description
Given an integer n, count how many prime numbers are strictly less than n. A prime is a whole number greater than 1 whose only positive divisors are 1 and itself.
For small inputs a divisibility test per candidate is fine, but as n grows you want a method that shares work across candidates rather than testing each number in isolation.
Example 1
Input: n = 10
Output: 4
The primes below 10 are 2, 3, 5, and 7, which is four values.
Example 2
Input: n = 2
Output: 0
There are no primes strictly less than 2, so the answer is 0.
Constraints
0 <= n <= 5 * 10^6The count includes only primes strictly less than n
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Indivisible Catalogue Numbers is our own problem on the technique behind Count Primes: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free