博客
关于我
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/

    你可能感兴趣的文章
    NIO Selector实现原理
    查看>>
    nio 中channel和buffer的基本使用
    查看>>
    NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
    查看>>
    NI笔试——大数加法
    查看>>
    NLP 基于kashgari和BERT实现中文命名实体识别(NER)
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>