classSolution(object): defcountPrimes(self, n): """ :type n: int :rtype: int """ if n < 3: return0 primes = [True] * n for i inrange(2, int(n**0.5)+1): j = i k = j while j*k < n: primes[j * k ] = False k += 1 count_primes = 0 // [1] for i inrange(2, n): if primes[i]: count_primes += 1 return count_primes
从 [1] 到最后的代码可以改为:
1
returnsum(primes) - 2 // 0,1需要去掉
有个感觉很不错的写法:
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: # @param {integer} n # @return {integer} defcountPrimes(self, n): if n < 3: return0 primes = [True] * n primes[0] = primes[1] = False for i inrange(2, int(n ** 0.5) + 1): if primes[i]: primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) returnsum(primes)