204. 计数质数

题目描述:统计所有小于非负整数 的质数的数量。

示例:

输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。

质数就是除了 1 和本身找不到其他能除尽的数!
思路一:暴力法(超时)

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

思路二:优化暴力(超时),我们验证质数可以不需要小于它的数都验证

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

思路三:厄拉多塞筛法

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

思路四:综上一起优化

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)

链接:https://leetcode-cn.com/problems/count-primes/solution/qiu-zhi-shu-chao-guo-90-by-powcai/

原文地址:https://www.cnblogs.com/USTC-ZCC/p/12696208.html