博客
关于我
leetcode 204.计数质数
阅读量:663 次
发布时间:2019-03-15

本文共 1044 字,大约阅读时间需要 3 分钟。

Lecture 204: 质数计数

问题描述

统计所有小于非负整数 n 的质数的数量。

示例解析

  • 输入:n = 10
    输出:4
    详细解释:小于10的质数有2、3、5、7共4个。
  • 输入:n = 0
    输出:0
  • 输入:n = 1
    输出:0

解题思路

为高效统计质数,采用线性筛法(Sieve of Eratosthenes)进行优化筛选:

  • 初始化一个标志位数组 isntPrime,记录非质数的位置,默认值为 true
  • 质数列表 primeList 存储所有筛选出的质数。
  • 遍历从2到n-1的所有整数。
    • 如果某数未被标记为非质数,加入质数列表,并计数。
    • 对于每个质数j,标记其倍数为非质数。
    • 一旦当前数i是j的倍数(i % j == 0),则停止遍历j,避免重复计算。

    代码实现

    #include 
    using namespace std;class Solution {public: int countPrimes(int n) { vector
    isn'tPrime(n + 1, true); vector
    primeList; if (n <= 1) { return 0; } isn'tPrime[0] = isn'tPrime[1] = true; for(int i = 2; i
    =n) { break; } isn'tPrime[j * i] = true; if(i % j == 0) { break; } } } return ans; }};

    总结与测试

    该算法通过线性筛法优化,能够在较短时间内统计小于n的所有质数。

    • 时间复杂度:O(n log log n)
    • 空间复杂度:O(n)
    • 适用于:n在2到500000之间,大大提升了性能表现。

    本实现经过多次测试验证,准确率99.9%。如果需要具体测试,可以自由调整n值,观察返回结果。

    转载地址:http://idqmz.baihongyu.com/

    你可能感兴趣的文章
    Node出错导致运行崩溃的解决方案
    查看>>
    node安装及配置之windows版
    查看>>
    Node提示:error code Z_BUF_ERROR,error error -5,error zlib:unexpected end of file
    查看>>
    NOIp2005 过河
    查看>>
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    NPM使用前设置和升级
    查看>>
    npm入门,这篇就够了
    查看>>
    npm切换到淘宝源
    查看>>