Leetcode-204. 计数质数

LeetCode - #204 计数质数 我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。LeetCode 算法到目前我们已经更新到 203 期,我们会保持更新时间和进度(周一、周三、周五早上 9:00 发布),每期的内容不多,我们希望大家可以在上班路上阅读,长久积累会有很大提升。不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。难度水平:中等。 阅读详情

Leetcode-204. 计数质数

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

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

思路:

     用dp数组存放该位置上的数值是否为质数。
     第一次循环遍历每个数的时候,并且把其小于n的倍数dp位置上都置为false;统计位置上为true 的数字的个数。

C++ code:

class Solution {
public:
    int countPrimes(int n) {
        vector<int> dp(n, 1);
        int res = 0;
        for(int i = 2; i < n; i++){
            if(dp[i]){
                res++;
                for(int j = 2 * i; j < n; j += i){
                    dp[j] = 0;
                }
            }
        }
        return res;
    }
};
LiteOS | 基于LiteOS的智慧农业案例实验分享 分享一个基于小熊派+LiteOS+华为云的案例实验(智慧农业)。 实验框图 相关模块简介 1、STM32L431RCT6 2、LiteOS LiteOS是华为开发的轻量级实时操作系统: LiteOS源码GitHub仓库链接: https://github.com/LiteOS/LiteOS 其源码一级目录结构如下: 其内核包括任务管理、内存管理、时间管理、通信机制、中断管理、队列管... 阅读详情

相关推荐

Windows系统监控实战:Grafana+Prometheus+node_exporter配置全攻略

本文提供了一套完整的Windows系统监控解决方案,详细介绍了如何使用Grafana、Prometheus和node_exporter(Windows版为windows_exporter)构建可视化监控平台。从环境准备、组件安装配置,到数据可视化与常见问题排查,手把手指导您实现从数据采集到仪表盘展示的全过程,帮助您从被动救火转向主动预警,有效保障Windows服务器稳定运行。

assembly8low的博客 254

【中等】力扣算法题解析LeetCode204:计数质数

本文介绍了利用优化的埃拉托斯特尼筛法统计小于n的质数数量的方法。核心思路是通过预处理偶数和只检查奇数来提高效率,同时从i²开始标记非质数以减少重复操作。算法时间复杂度接近O(n log log n),适用于大数范围(n ≤ 5×10⁶)。代码实现使用布尔数组标记非质数,并通过步长优化减少计算量。最终返回质数计数器结果。

ylumwd的博客 913

对族实例进行任意的矩阵变换,需要什么样的族?

问:一个小问题,想向您请教一下。 能不能实现一个这样的操作:创建了一个常规模型的FamilyInstance,然后知道旋转和平移的矩阵,能否根据变换矩阵更新FamilyInstance的位置,绕任意轴旋转任意角度。 请问什么样的实体才能在revit项目文件中任意旋转?貌似一般的实例只能在XY平面内旋转,并且LocationPoint中只有一个Rotation参数。答:您好,因为Revit里面的构件

我爱Revit —— BIM应用及BIM应用软件解决方案专栏 3632

力扣第204题“计数质数”

本文详细解读了力扣第204题“计数质数”,通过使用埃拉托色尼筛法高效地解决了这一问题,并提供了详细的解释和模拟面试问答。希望读者通过本文的学习,能够在力扣刷题的过程中更加得心应手。

10年数据\经营分析经验,现任大厂数据分析负责人 1405

Debezium系列之:使用指定值替代指定字段的值

Debezium系列之:使用指定值替代指定字段的值

zhengzaifeidelushang的博客 309

【VoxCPM2】在Windows上从零搭建VoxCPM2 语音生成和语音克隆AI算法

建议你了解清楚VoxCPM2,再来考虑是否需要自己在本地搭建。

AnChenliang_1002的博客 764

LeetCode第204题_计数质数

LeetCode第204题要求统计小于给定整数n的质数数量。题目提供了两种主要解法:埃拉托斯特尼筛法(埃氏筛)和线性筛(欧拉筛)。埃氏筛通过标记质数的倍数来筛选合数,时间复杂度为O(n log log n),空间复杂度为O(n)。线性筛进一步优化,确保每个合数只被其最小质因子筛选一次,时间复杂度为O(n),空间复杂度仍为O(n)。代码实现包括C#、Python和C++版本,分别展示了两种筛法的具体步骤和优化点。

qq_40263592的博客 1410

增量学习入门:概念、代码示例与应用场景

在当今快速变化的数据环境中,传统的机器学习模型往往需要重新训练以适应新的数据。然而,这种方法不仅耗时耗力,还可能导致模型性能的不稳定。增量学习(Incremental Learning)作为一种新兴的学习范式,能够在新数据到来时动态更新模型,而无需重新训练整个模型。本文将详细介绍增量学习的基本概念、代码示例、应用场景以及需要注意的事项。增量学习作为一种高效的机器学习方法,能够在新数据到来时动态更新模型,具有广泛的应用前景。通过本文的介绍,相信你对增量学习有了初步的了解。

加入“Super Entity”,与全能开发团队共探AI智能体与数字人项目,开启前沿技术之旅。 1162

leetcode 204. 计数质数

leetcode 204. 计数质数 题目描述 统计所有小于非负整数 n 的质数的数量。 示例: 输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 解题思路 普通的做法是遍历所有的数去找因数,这样复杂度太高, 这里采用厄拉多塞筛法,思想是假如当前数是i,那么范围n内所有i 的倍数肯定不是质数,用一个bool数组记录下来。 这里推荐大家看一下这...

EngineerHe的博客 700

PostgreSQL的学习心得和知识总结(一百二十六)|深入理解PostgreSQL数据库SQL执行时间计算 \timing 和 log_duration的使用和原理

1、参考书籍:《PostgreSQL数据库内核分析》2、参考书籍:《数据库事务处理的艺术:事务管理与并发控制》3、

孤傲小二~阿沐的博客 995

OpenMM | PDBFixer 用于蛋白质预处理

PDBFixer 用于蛋白质预处理

DrugOne 3014

LeetCode第 204 题:计数质数(C++)

204. 计数质数 - 力扣(LeetCode) 质数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。 如果一个数不是素数是合数, 那么一定可以由两个自然数相乘得到, 其中一个大于或等于它的平方根,一个小于或等于它的平方根,并且成对出现。所以判断n是不是质数,只需要判断2 ~ sqrt(n)之间的数字能不能被n整除就可以了。 相对暴力 class Solution { public: int countPrimes(int n) { int cnt = 0;

zj 793

华为OD机试双机位C卷-部门人力分配 (Py/Java/C/C++/Js/Go)

华为OD机试(机考)双机位C卷 【部门人力分配】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试 - 部门人力分配。

qq_45776114的博客 1881

Leetcode204--计数质数

Leetcode204–计数质数 统计所有小于非负整数 n 的质数的数量。 编程语言:python 作者:黑暗主宰 邮箱:shengzhanhe@gmail.com 文章目录Leetcode204--计数质数题目描述解题思路 Leetcode204–计数质数 题目描述 原题链接: ​ https://leetcode-cn.com/problems/count-primes/ (中文) ​ h...

EngineerHe的博客 580

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

Leetcode204. 计数质数(C语言)

Leetcode204. 计数质数(C语言) 算法-分治:算法与数据结构参考 题目: 统计所有小于 非负整数 n 的质数的数量。例: 输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 思路: 厄拉多塞筛法:先去掉2的倍数;然后3的倍数;(4是2的倍数,过滤);5的倍数;(6是2和3的倍数);7的倍数。。。直到sqrt(n)。 注意:可以按照定义...

jeanlu的博客 464

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

【LeetCode】204. 计数质数

题目 统计所有小于非负整数n的质数的数量。 示例 1: 输入:n = 10 输出:4 解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 示例 2: 输入:n = 0 输出:0 示例 3: 输入:n = 1 输出:0 提示: 解题思路 前言 统计 [2,n] 中质数的数量是一个很常见的题目,也有很多巧妙高效的做法,接下来的部分只会讲述一些常见的做法,更多的拓展内容读者可以自行搜索补充,也欢迎在评论区与大家分享交流。 方法一:枚举 很直观的思...

jiiiiiaaaa的博客 511

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

力扣LeetCode 204. 计数质数

用一个vector记录出现过所有质数,因为一个数字可以被分为很多个质数相乘,所以记录一个数字是不是质数,只要看它能不能被其它质数整除,所以只要用1——n的数字去除以 vector中的质数,只要能被其中一个质数整除就说明不是质数,转到下一个数字,如果除以所有vector中质数后都不能被除尽,说明为质数,将其放入vector中。 class Solution { public: int countPrimes(int n) { if(n<=2){//排除特殊情况.

weixin_43304992的博客 271

【LeetCode每日一题】——204.计数质数

给定整数 n ,返回 所有小于非负整数 n 的质数的数量 。

IronmanJay 1685

LeetCode 204. 计数质数 | Python

思路:埃氏筛

"大梦三千秋的博客 687

Leetcode 204. 计数质数 C++

Leetcode 204. 计数质数 题目 统计所有小于非负整数 n 的质数的数量。 示例: 输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 题解 暴力,如果数num可以整除i,则num不是质数,其中遍历的时候只需要i<sqrt(num)+1。详细过程见代码 代码 int isPrime(int n){ for(int i=2; i<sqrt(n)+1; i++){ if(n % i == 0) r

weixin_43750513的博客 203

力扣(leetcode) 204. 计数质数 (埃氏筛)

题目在这:https://leetcode-cn.com/problems/count-primes/

深度不学习!!的博客 1104

Leetcode204. 计数质数

Leetcode204. 计数质数 题目: 统计所有小于非负整数 n 的质数的数量。 示例: 输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 题解: 质数是因子为1和本身, 如果数c不是质数,则还有其他因子,其中的因子,假如为a,b.其中必有一个大于sqrt(c)sqrt(c)sqrt(c) ,一个小于sqrt(c)sqrt(c)sqrt(c...

会流泪de鱼的博客 251

[力扣刷题]204. 计数质数

[力扣刷题]204. 计数质数 添加链接描述 统计所有小于非负整数 n 的质数的数量。 1.暴力法超时 2.素数筛 思路:用额外bool数组存每个数是否需要判断标记,若发现一个质数,则其倍数全都不需要再进行判断。 class Solution { public: int countPrimes(int n) { if(n < 3) return 0; vector<bool> isPrime(n + 1, true); for(int

weixin_45459322的博客 134

LeetCode204.计数质数Golang版

LeetCode204.计数质数Golang版 1. 问题描述 统计所有小于非负整数 n 的质数的数量。 示例 1: 输入:n = 10 输出:4 解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 示例 2: 输入:n = 0 输出:0 示例 3: 输入:n = 1 输出:0 2. 思路 厄拉多塞筛法(Eratosthenes)。 从2开始,2的倍数全部去掉;接下来3是质数,3的倍数全部去掉,如此下去,留下的都是质数。 初始化一个大小为n的boll类型数组,遍历2到n,如果为fa

菜到不敢run 155

力扣-204 计数质数

力扣-204 计数质数 这题用普通的质数筛选方法直接就给你超时了,所以我们肯定得用其他的方法,对算法进行改进 埃式筛 思路就是,先定义一个数组进行标记。 开始定义这个数组所表示的数全部都是质数,然后开始筛选。 假如这个数是质数,那么这个数的倍数就全部都被筛选下来了。 AC Code class Solution { public: bool ret[10000006]; int countPrimes(int n) { int ans =0; if(n

hero_th的博客 426

Leetcode 每日一题——204. 计数质数

204. 计数质数 统计所有小于非负整数 n 的质数的数量。 质数统计虽然是个简单的题目,但是如果不了解数学的意义还是有点难处理的,下面是枚举法的C++代码: class Solution { public: int countPrimes(int n) { int res=0; for(int i=2; i<n; i++) { res+=isPrime(i); } return res;

qq_41978896的博客 215
上一篇: Leetcode-304. 二维区域和检索 - 矩阵不可变
下一篇: Leetcode-5. 最长回文子串
WangXu__
博客等级 码龄9年 3粉丝 156原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址