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 −
Let us see the following implementation to get a better understanding −
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))
n = 50 n = 10