Count Primes in Python


Suppose we have a limit n. We have to count the number of primes present in the range 2 to n. So if n = 10, the result will be 4. As there are four primes before 10, they are 2, 3, 5, 7.

To solve this, we will follow this approach −

  • count = 0
  • take one array prime = of size n + 1, and fill it with False
  • for i = 0 to n, do
    • if prime[i] = false, then
      • increase count by 1
      • set j = 2
      • while j * i <n, then
        • prime[i * j] = True
        • j = j + 1
  • return count

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def countPrimes(self, n):
      """
      :type n: int
      :rtype: int
      """
      count = 0
      primes = [False for i in range(n+1)]
      for i in range(2,n):
         if primes[i] == False:
            count+=1
            j = 2
            while j*i<n:
               primes[j*i] = True
               j+=1
      return count
ob1 = Solution()
print(ob1.countPrimes(50))
print(ob1.countPrimes(10))

Input

n = 50
n = 10

Output

15
4

Updated on: 28-Apr-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements