【问题标题】:C++ sieve of Eratosthenes with array [closed]带有数组的 Eratosthenes 的 C++ 筛子[关闭]
【发布时间】:2013-08-18 17:45:22
【问题描述】:
我想只使用数组在 C++ 中编写著名的埃拉托色尼筛法,因为它是一个集合,我可以在其中删除一些元素以找出素数。
我不想使用 STL(向量,集合)......只是数组!怎么实现?
我试图解释为什么我不想使用 STL 集合运算符:我从一开始就在学习 C++,我认为 STL 当然对程序员有用,但建立在标准库上,所以我想使用以前的运算符和命令。我知道使用 STL 一切都会变得更简单。
【问题讨论】:
标签:
c++
arrays
stl
sieve-of-eratosthenes
【解决方案1】:
the sieve of Eratosthenes效率的关键在于它不重复不,删除⁄删除⁄扔掉⁄等等。 , 而只是标记它们。
保留所有数字可以保留我们使用数字值作为其在此数组中的地址并因此直接寻址它的能力:array[n]。当在现代random-access memory 计算机上实施时(就像integer sorting algorithms 一样),这就是使筛子的枚举和标记每个素数的倍数有效的原因。
为了使该数组模拟一个集合,我们为每个条目提供两个可能的值,即标志:on 和 off、prime 或 composite、1 或 0。是的,我们实际上只需要一个位,而不是字节,来表示筛数组中的每个数字,假设我们在处理它时不会删除它们中的任何一个。
顺便说一句,vector<bool> 被自动打包,以位表示bools。很方便。
【解决方案2】:
来自Algorithms and Data Structures
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
void runEratosthenesSieve(int upperBound) {
int upperBoundSquareRoot = (int)sqrt((double)upperBound);
bool *isComposite = new bool[upperBound + 1];
memset(isComposite, 0, sizeof(bool) * (upperBound + 1));
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) {
cout << m << " ";
for (int k = m * m; k <= upperBound; k += m)
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++)
if (!isComposite[m])
cout << m << " ";
delete [] isComposite;
}
int main()
{
runEratosthenesSieve(1000);
}
您不想使用 STL,但这不是一个好主意
STL 让生活变得更简单。
仍然考虑使用std::map这个实现
int max = 100;
S sieve;
for(int it=2;it < max;++it)
sieve.insert(it);
for(S::iterator it = sieve.begin();it != sieve.end();++it)
{
int prime = *it;
S::iterator x = it;
++x;
while(x != sieve.end())
if (((*x) % prime) == 0)
sieve.erase(x++);
else
++x;
}
for(S::iterator it = sieve.begin();it != sieve.end();++it)
std::cout<<*it<<std::endl;