问题描述
我正在编写 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;
}
我想问的问题如下:
- C++ 中有 for-all 类型语言结构吗?
- 如果没有,是否有更合适的方式来实现上述想法?尤其是我对计数器变量的使用不赞成吗?
- (奖金)有没有人知道一种更有效的方法来找到所有的素数?上述方法在高达 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 (将#修改为@)