Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
思路:一个找质数的算法.最开始的思路是将质数保存在一个数组primenums中,输入n后,用while循环.对于数i,与质数数组中每个数进行取余运算.如果余数为零,则说明不是质数,i加一后break当前循环;如果与质数数组中所有数取余运算都没有0,说明是新的质数,添加到数组中.最后返回数组长度,也就是质数个数.然而如果测试数字过大的话,提交后会显示超时.
class Solution:
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n<3:
return 0
primenums = [2]
i=2
while i<n:
for num in primenums:
if i%num == 0:
i += 1
break
if num == primenums[-1]:
primenums.append(i)
i += 1
break
return len(primenums)
后来看了看别人的思路,发现一个新思路.利用埃拉托斯特尼筛法.时间复杂度为O(nloglogn).还有改进空间
class Solution:
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n<3:
return 0
isPrime = [True]*n
isPrime[0] = isPrime[1] = False
for i in range(2,int(n**0.5)+1):
if isPrime[i]:
isPrime[i*i:n:i] = [False]*len(isPrime[i*i:n:i])
return sum(isPrime)