MediumArrayMathNumber Theory

Count Primes

LeetCode
1 approach, code in all languages

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^6
  • The count includes only primes strictly less than n
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now