原题链接:Count Primes
题目内容:
Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
统计小于n的所有质数的数量,其中n是非负数
Python.01
易知:
- 所有的质数除了1和它本身以外不再有其他因数。
- 一个数n,若小于√n的数中没有除了1以外的因数,那么大于√n的数中也没有。
- 类似筛选法的思想,从已知的质数序列中取数字作为因数验证当前的数字是否为质数。
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
primes = list([2])
def check_primes(cp, primes):
for i in primes:
if cp % i == 0 and i * i <= cp:
return False
return True
for j in range(2, n):
if check_primes(j, primes):
primes.append(j)
return len(primes) - 1
这个方法会重复验证2,所以最后的长度-1
虽然结果正确,但是会超时。
Python.02
- 投入埃拉托斯特尼筛法的怀抱~
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n < 2:
return 0
primes = [True for i in range(1,n)]
primes[0] = False
i = 2
count = 0
while i*i < n:
if primes[i-1]:
for j in range(i*i, n, i):
primes[j-1] = False
i += 1
for num in primes:
if num:
count += 1
return count
- 需要注意的一点是0,1的处理,题目中指出是非负数。