KatInterview

204. Count Primes

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to count the number of prime numbers strictly less than a given non-negative integer n. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Solution

Count Primes in Python

class Solution:
    def countPrimes(self, n: int) -> int:
        # Handle edge cases where n is 0, 1, or 2.
        if n <= 2:
            return 0
        
        # Create a boolean list to mark numbers as prime or not.
        # Initialize all numbers up to n as potentially prime (True).
        is_prime = [True] * n
        is_prime[0] = False
        is_prime[1] = False
        
        # Sieve of Eratosthenes algorithm
        # Loop from 2 up to the square root of n.
        # int(n**0.5) + 1 is used to create the correct range.
        for p in range(2, int(n**0.5) + 1):
            # If is_prime[p] is True, then p is a prime number.
            if is_prime[p]:
                # Mark all multiples of p as not prime.
                # We can start marking from p*p.
                # The slice assignment is a concise way to do this in Python.
                # It sets all elements from index p*p to n, with a step of p, to False.
                for i in range(p * p, n, p):
                    is_prime[i] = False

        # Summing the boolean list directly counts the number of True values.
        # We are interested in primes from 2 to n-1.
        count = 0
        for i in range(2, n):
            if is_prime[i]:
                count += 1
        return count
        # A more Pythonic way to count is: return sum(is_prime[2:])

Count Primes in Java

import java.util.Arrays;

class Solution {
    public int countPrimes(int n) {
        // Handle edge cases where n is 0, 1, or 2.
        if (n <= 2) {
            return 0;
        }

        // Create a boolean array to mark numbers as prime or not.
        // Initialize all numbers up to n as potentially prime (true).
        boolean[] isPrime = new boolean[n];
        Arrays.fill(isPrime, true);

        isPrime[0] = false;
        isPrime[1] = false;

        // Sieve of Eratosthenes algorithm
        // Loop from 2 up to the square root of n.
        for (int p = 2; p * p < n; p++) {
            // If isPrime[p] is true, then p is a prime number.
            if (isPrime[p]) {
                // Mark all multiples of p as not prime.
                // We can start marking from p*p, because smaller multiples
                // would have already been marked by smaller primes.
                for (int i = p * p; i < n; i += p) {
                    isPrime[i] = false;
                }
            }
        }

        // Count the number of primes.
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (isPrime[i]) {
                count++;
            }
        }

        return count;
    }
}

Count Primes in C++

class Solution {
public:
    int countPrimes(int n) {
        // Handle edge cases where n is 0, 1, or 2.
        if (n <= 2) {
            return 0;
        }

        // Create a boolean vector to mark numbers as prime or not.
        // Initialize all numbers up to n as potentially prime.
        // std::vector<bool> is a space-optimized specialization of std::vector for bools.
        std::vector<bool> isPrime(n, true);
        isPrime[0] = false;
        isPrime[1] = false;

        // Sieve of Eratosthenes algorithm
        // Loop from 2 up to the square root of n.
        // Any composite number will have a prime factor less than or equal to its square root.
        for (int p = 2; p * p < n; ++p) {
            // If isPrime[p] is true, then p is a prime number.
            if (isPrime[p]) {
                // Mark all multiples of p as not prime.
                // We can start marking from p*p, because smaller multiples like 2*p, 3*p
                // would have already been marked by smaller primes (2, 3, etc.).
                for (int i = p * p; i < n; i += p) {
                    isPrime[i] = false;
                }
            }
        }

        // Count the number of primes.
        int count = 0;
        for (int i = 2; i < n; ++i) {
            if (isPrime[i]) {
                count++;
            }
        }

        return count;
    }
};

Count Primes in TypeScript

function countPrimes(n: number): number {
    // Handle edge cases where n is 0, 1, or 2.
    if (n <= 2) {
        return 0;
    }

    // Create a boolean array to mark numbers as prime or not.
    // Initialize all numbers up to n as potentially prime (true).
    const isPrime = new Array(n).fill(true);
    isPrime[0] = false;
    isPrime[1] = false;

    // Sieve of Eratosthenes algorithm
    // Loop from 2 up to the square root of n.
    for (let p = 2; p * p < n; p++) {
        // If isPrime[p] is true, then p is a prime number.
        if (isPrime[p]) {
            // Mark all multiples of p as not prime.
            // We can start marking from p*p, because smaller multiples
            // would have already been marked by smaller primes.
            for (let i = p * p; i < n; i += p) {
                isPrime[i] = false;
            }
        }
    }

    // Count the number of primes.
    let count = 0;
    for (let i = 2; i < n; i++) {
        if (isPrime[i]) {
            count++;
        }
    }

    return count;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.