mycode     time limited

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 3: return 0
      
        def is_primes(x):
            for i in range(2,x):
                if x % i == 0:
                    return False
            return True
        
        count = 0
    
        for i in range(2,n):
            if is_primes(i) :
                print(i)
                count += 1 
        return count
            

 

参考 

1  

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 2:
            return 0
        
        prime = [1] * n
        prime[0] = prime[1] = 0
        
        for index in range(2, n):
            if prime[index] == 1:
                time = 2
                while index * time < n:
                    prime[index * time] = 0
                    time += 1
                    
        return sum(prime)    

2

class Solution:
    def countPrimes(self, n: int) -> int:
        if n < 2: return 0
        
        prime = [1]*n
        
        for i in range(2,int(n*0.5)+1):
            prime[i*i:n:i] = [0] * len(prime[i*i:n:i])
        
        return sum(prime)-2 #-2 because 0 and 1 is not a prime number

更快优化

import math

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        
        if n < 2:
            return 0
        s = [1] * n
        s[0] = s[1] = 0
        for i in range(2, int(n ** 0.5) + 1):
            if s[i] == 1:
                s[i*i:n:i] = [0] * int((n-i*i-1)/i + 1)               
        return sum(s)

 

 

time limited

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        for i in range(2,n):
            count += self.isPrime(i)     
        return count

    def isPrime(self,x):
        x_= int(x**0.5+1)
        for i in range(2,x_):
            if x % i == 0:
                return 0
        return 1