Topic links: https://leetcode-cn.com/problems/count-primes/
Subject description:
All statistical non-negative integers less than n number of prime numbers.
Example:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
Ideas:
Prime number is in addition to 1
and in itself can not find other number divisible, see the topic ideas tips!
A thought: Violence Act (timeout) (you can learn about for ... else
usage, with the general break
use)
class Solution:
def countPrimes(self, n: int) -> int:
res = 0
for i in range(2, n):
for j in range(2, i):
if i % j == 0:
break
else:
#print(i)
res += 1
return res
Ideas II: optimization of violence (timeout), we can not require verification prime number less than its number are verified
class Solution:
def countPrimes(self, n: int) -> int:
res = 0
for i in range(2, n):
for j in range(2, int(i ** 0.5) + 1):
if i % j == 0:
break
else:
# print(i)
res += 1
return res
Thinking three: Eladuose sieve (seems able to live)
class Solution:
def countPrimes(self, n: int) -> int:
isPrimes = [1] * n
res = 0
for i in range(2, n):
if isPrimes[i] == 1: res += 1
j = i
while i * j < n:
isPrimes[i * j] = 0
j += 1
return res
Ideas Four: Comprehensive Optimization (over 90%) with the
class Solution:
def countPrimes(self, n: int) -> int:
if n < 2: return 0
isPrimes = [1] * n
isPrimes[0] = isPrimes[1] = 0
for i in range(2, int(n ** 0.5) + 1):
if isPrimes[i] == 1:
isPrimes[i * i: n: i] = [0] * len(isPrimes[i * i: n: i])
return sum(isPrimes)