在 C++ 代码中使用计数器查找素数

如何解决在 C++ 代码中使用计数器查找素数

我正在编写 C++ 代码来列出 1 到 100 之间的所有素数。为了提出我的问题,我需要提供一些背景信息。

我想做的基本思路如下:

引入一个向量,以升序保存所有素数。如果给出了该向量的前 j 个元素,则 j+1 元素将作为大于第 j 个元素的最小整数给出,该元素不能被前 j 个元素中的任何一个整除。此外,第一个元素被赋予 2。

因此,如果 v 表示素数向量,我想生成实现以下数学类型参数的代码;

v[1]=2;
for(2<i<=100)
             if i % v[j] !=0 FOR ALL 0<j< v.size()
                v.push_back(i)
             else
                do nothing

然而,我面临的问题是 C++ 似乎没有适用于所有类型语言的构造。为了解决这个问题,我引入了一个计数器变量。更准确地说:

int main() {
    
    const int max=100;
    vector<int>primes; // vector holding list of primes up to some number.
    
    for(int i=2; i<=max;++i){
        if(i==2)
            primes.push_back(i); // inserts 2 as first prime
        else{
            double counter=primes.size(); // counter to be used in following loop. 
            for(int j=0;j<primes.size();++j){
                
                if(i% primes[j]==0){
                    break; // breaks loop if prime divisor found!
            }
                else{
                    counter-=1; //counter starts at the current size of the primes vector,and 1 is deducted each time an entry is not a prime divisor.
        }
            
            }
            if (counter==0) // if the counter reaches 0 then i has no prime divisors so must be prime.
                primes.push_back(i);
            
        }
    }
        for(int i=0; i<primes.size(); ++i){
            cout << primes[i] << '\t';
        }
        
    return 0;
}

我想问的问题如下:

  1. C++ 中有 for-all 类型语言结构吗?
  2. 如果没有,是否有更合适的方式来实现上述想法?尤其是我对计数器变量的使用不赞成吗?
  3. (奖金)有没有人知道一种更有效的方法来找到所有的素数?上述方法在高达 1,000,000 时效果相对较好,但在高达 10 亿时效果不佳。

请注意,我是 C++ 和一般编码的初学者(目前正在阅读 Stroustrup 的书),因此我们将不胜感激。

提前致谢!

编辑:

大家好,

感谢您的评论。从他们那里我了解到计数器和 for all 类型语句的使用都是不必要的。相反,可以为每个整数分配一个真值或假值,指示一个数是否是素数,只将具有真值的整数添加到向量中。以这种方式进行设置还允许在给定currently known'' primes to be independent of the process of updating the 当前已知的素数的情况下检查一个数是否是素数的过程。因此,这解决了对我的代码的另一个批评,即它试图一次做太多事情。

最后有人向我指出,有一些基本方法可以提高素数除数算法查找素数的效率,例如,在搜索中打折所有大于 2 的偶数(通过启动适当的循环来实现)在 3,然后在每个阶段增加 2)。更普遍地注意到,像埃拉斯托提尼筛法这样的算法在寻找素数时要快得多,因为这些算法是基于乘法而不是除法。最终代码如下:

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

vector<int> primes; // vector holding list of primes up to some number.

bool is_prime(int n) {// Given integer n and a vector of primes this boolean valued function returns false if any of the primes is a prime divisor of n,and true otherwise. In the context of the main function,the list of primes will be all those that precede n,hence a return of a true value means that n is itself prime. Hence the function name.

    for (int p = 0; p < primes.size(); ++p)
        if (n % primes[p] == 0) { 
            return false;
                   break; // Breaks loop as soon as the first prime divisor is found.
        }
    return true;
}

int main() {
    
    const int max=100; 
    
    primes.push_back(2);

    for (int i = 3; i <= max; i+=2)
        if (is_prime(i) == true) primes.push_back(i);

    for(int i=0; i<primes.size(); ++i)
            cout << primes[i] << '\t';
       
    return 0;
}

我还有一个问题:我检查了算法达到 1,000 需要多长时间,并且 is_prime 函数(一旦找到素数除数就停止搜索)似乎没有出现中断来影响时间。为什么会这样?

感谢大家的帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-