DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Count Primes

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

Example 1:

Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Example 2:

Input: n = 0
Output: 0

Example 3:

Input: n = 1
Output: 0

Constraints:

  • 0 <= n <= 5 * 106

SOLUTION:

import math

class Solution:
    def countPrimes(self, n: int) -> int:
        if n <= 2:
            return 0
        primes = [1] * n
        primes[0] = 0
        primes[1] = 0
        numprimes = n - 2
        l = int(math.sqrt(n)) + 1
        for i in range(2, l):
            if primes[i] == 0:
                continue
            for j in range(i, 1 +  n // i):
                if i * j < n and primes[i * j] == 1:
                    primes[i * j] = 0
                    numprimes -= 1
        return numprimes
Enter fullscreen mode Exit fullscreen mode

Top comments (0)