【发布时间】:2016-08-29 17:38:57
【问题描述】:
我已经在 C++ 中实现了 Eratosthenes 的 Sieve,但是输入大于 10^10 时代码会崩溃。编译器显示信号 11(SIGSEV)。这是因为全局数组 bool a[5000000000000000];。要检查高达 10^16 的奇数,我将数组大小设为 (10^16)/2 = 5 * 10^15。如何减少空间?
这个问题有一个答案How do i reduce the space complexity in Sieve of Eratosthenes to generate prime between a and b?我相应地尝试了,但是我的程序崩溃了。有人可以提供实现细节来解决它吗?
#include <bits/stdc++.h>
using namespace std;
long long unsigned n,sqN;
bool a[5000000000000000];
long long int sieve_of_Eratosthenes();
int main()
{
cout<<"Enter upper bound to generate prime upto:"<<endl;
cin>>n;
long long int count = sieve_of_Eratosthenes();
cout<<"Total = "<<count<<endl;
return 0;
}
long long int sieve_of_Eratosthenes()
{
long long unsigned i,j,count = 0;
sqN = (long long unsigned) sqrt(n);
for(i=3; i<=sqN; i+=2)
{
if(a[i/2]==true)
{
continue;
}
for(j = i*i; j<=n; j+=(2*i))
{
a[j/2] = true;
}
}
if(n>=2)
{
count++;
cout<<2<<endl;
}
for(i=3; i<=n; i+=2)
{
if(a[i/2]==false)
{
cout<<i<<endl;
count++;
}
}
return count;
}
【问题讨论】:
-
vector<bool>可以以这样一种方式实现,即您可以获得令人难以置信的大小,但会以性能为代价来打包和解包位。配置文件以查看它是否适合您。 -
我想看看能在堆栈或任何地方分配这么多内存的计算机。
-
伙计们,他把它作为一个全局的,所以除非你正在处理一个真正的 strange 实现,否则它永远不会在堆栈上。
-
我想到了在 c++ 中使用
std:bitset。它肯定会减少空间。试试看怎么样? -
Google 告诉我存储 bool 数组需要 5 PB。唔。更好地减少问题规模..