[英]Find prime numbers between 1 and ~2^128
I want to implement an algorithm to get a list of prime numbers between 1 and a very large number. 我想实现一个算法来获得1和非常大的数字之间的素数列表。 I was going to use erasthosthenes sieve. 我打算用erasthosthenes筛子。 But to implement the sieve, shouldn't we first create a boolean array containing that many numbers. 但是要实现筛子,我们不应该首先创建一个包含那么多数字的布尔数组。 Isn't that very memory consuming? 这不是很耗费内存吗? Is there an alternative to do this? 有替代方法吗?
Though you may never be able to store 2^128 , I made a program in c++ using erasthosthenes sieve where I consider only 10^5 elements at a time thus eliminating storage constraint. 虽然你可能永远无法存储2 ^ 128,但我使用erasthosthenes sieve在c ++中创建了一个程序,我一次只考虑10 ^ 5个元素,从而消除了存储限制。
Usage ./a.out left1 right1 left2 right2 ... You can do the same in python 用法./a.out left1 right1 left2 right2 ...你可以在python中做同样的事情
#include<iostream>
#include<stdlib.h>
using namespace std;
int main(int argc,char ** argv){
int prime[100001];
long long l,r;
if((argc-1)%2!=0) cout<<"Invalid arguments: One limit missing"<<endl;
for(long i=0;i<=100001;++i)
prime[i]=1;
prime[0]=prime[1]=0;
for(long i=2;i*i<=100000;++i){
if(prime[i]==1){
for(long j=i+i;j<=100000;j=j+i)
prime[j]=false;
}
}
int cnt=1;
while(cnt<argc){
l=atol(argv[cnt]);
r=atol(argv[cnt+1]);
cnt=cnt+2;
int f=1;
if(r<=100000){
for(long i=l;i<=r;++i){
if(prime[i]){
cout<<i<<endl;
}
}
cout<<endl;
f=0;
}
if(!f) continue;
bool ans[100000]={true};
long long temp=r;
while(temp>l){
r=min(temp,l+100000);
for(long long i=0;i<100000;++i) ans[i]=true;
for(long long i=2;i*i<=r;++i){
if(prime[i]){
long k=l/i;
k=k*i;
if(k<l) k+=i;
if(k==i) k+=i;
for(;k<=r;k=k+i){
ans[k-l]=false;
}
}
}
for(long i=0;i<r-l+1;++i)
if(ans[i]) cout<<l+i<<endl;
cout<<endl;
l=l+100001;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.