DevPath

← All problems

Count Primes Below N

Medium math · sieve

Description

Return the number of prime numbers strictly less than n.

Constraints

0 <= n <= 10^6

Examples

Input: n = 10

Output: 4

2, 3, 5, 7

Hints (1)
  • Sieve of Eratosthenes.

Solutions

Sieve of Eratosthenes. · Time O(n log log n) · Space O(n)

func countPrimes(n int) int {
    if n < 3 {
        return 0
    }
    sieve := make([]bool, n)
    for i := range sieve {
        sieve[i] = true
    }
    sieve[0], sieve[1] = false, false
    for i := 2; i*i < n; i++ {
        if sieve[i] {
            for j := i * i; j < n; j += i {
                sieve[j] = false
            }
        }
    }
    count := 0
    for _, p := range sieve {
        if p {
            count++
        }
    }
    return count
}

Create a free account to submit solutions, track progress and save problems.

Create account