zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    信息安全系统设计基础第四周学习内容
    信息安全系统设计基础第三周学习总结
    第十二节 Linux下软件安装
    第十一节 正则表达式基础
    session的生命周期
    session对象
    什么是session
    请求重定向和请求转发的关系
    java web的response对象
    java web中request对象(下)
  • 原文地址:https://www.cnblogs.com/USTC-ZCC/p/12696208.html
Copyright © 2011-2022 走看看