Algo-Sim › Math & Geometry

Count Primes (Sieve of Eratosthenes)

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Cross out multiples of each prime starting at p². What survives is prime. O(n log log n) for every number below n at once.

Problem

Given an integer n, return the number of prime numbers that are strictly less than n.

Constraints

Edge cases to test

Follow-up questions

Why start crossing out at p²?
Smaller multiples k·p with k < p were already crossed out by k’s prime factors.
What if n is too big for one array?
A segmented sieve: sieve the primes up to √n, then each block of size √n: O(√n) memory.

Solution

Java

public int countPrimes(int n) {
    if (n < 3) return 0;
    boolean[] composite = new boolean[n];
    for (int p = 2; (long) p * p < n; p++) {
        if (composite[p]) continue;
        for (int m = p * p; m < n; m += p) composite[m] = true;
    }
    int count = 0;
    for (int i = 2; i < n; i++) if (!composite[i]) count++;
    return count;
}

Python

def count_primes(n):
    if n < 3:
        return 0
    composite = [False] * n
    p = 2
    while p * p < n:
        if not composite[p]:
            for m in range(p * p, n, p):
                composite[m] = True
        p += 1
    return sum(1 for i in range(2, n) if not composite[i])

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int countPrimes(int n) {
        if (n < 3)
            return 0;
        vector<bool> composite = vector<bool>(n);
        for (int p = 2; (long long)p * p < n; p++) {
            if (composite[p])
                continue;
            for (int m = p * p; m < n; m += p)
                composite[m] = true;
        }
        int count = 0;
        for (int i = 2; i < n; i++)
            if (!composite[i])
                count++;
        return count;
    }
};

More Math & Geometry problems