Count Primes

medium
math

Given a non-negative integer n, return the number of prime numbers that are strictly less than n.

A prime is a whole number greater than 1 whose only positive divisors are 1 and itself.

Input / output

  • Input: n: integer
  • Output: the count of primes below n

Examples

  1. n = 10 returns 4 (the primes 2, 3, 5, 7).
  2. n = 0 returns 0.
  3. n = 2 returns 0 (no primes are below 2).

Constraints

  • 0 <= n <= 5,000,000

Follow-up A trial-division scan is O(n * sqrt(n)). Can you reach O(n log log n) with the Sieve of Eratosthenes, and why is it safe to start crossing out multiples of p at p * p?

Examples

Example 1

Input: n = 10
Output: 4

Example 2

Input: n = 0
Output: 0

Example 3

Input: n = 2
Output: 0
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.