题目:
Count the number of prime numbers less than a non-negative number, n.
分析:
- 对于小于3整数特殊处理
- 定义判断素数函数
代码:
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
def isPrime(num):
if num % 2 == 0:
return 0
n = 3
while n ** 2 <= num:
if num % n == 0:
return 0
n += 2
return 1
if n <= 2:
return 0
i = 3
counts = 1
while i < n:
counts += isPrime(i)
i += 2
return counts
思考:
- 以上代码是传统思维,在leetcode直接超时
- 使用排除法,不断计算sqrt(n)以内每个整数在n以内的k倍数,直接排除
- 未被排除的即为素数
- 别人的代码如下(来自leetcode中tusizi)
class Solution:
# @param {integer} n
# @return {integer}
def countPrimes(self, n):
if n < 3:
return 0
primes = [True] * n
primes[0] = primes[1] = False
for i in range(2, int(n ** 0.5) + 1):
if primes[i]:
primes[i * i: n: i] = [False] * len(primes[i * i: n: i])
return sum(primes)