DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

2 1

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay