【发布时间】:2017-10-16 16:20:38
【问题描述】:
我目前正在尝试进一步优化我的筛子。我必须使用 eratosthenes 筛计算两个数字之间的素数,我知道需要工作的两个数字是 2000000000000 和 2000000100000。由于运行时间过长,我当前的代码出现分段错误。任何优化方面的帮助将不胜感激:
#include <iostream>
#include <cmath>
using namespace std;
double Sieve(long long a, long long b){
//Create array of type bool
bool *prime;
prime = new bool[b];
//Set all values in array to true
for (long i = 0; i < b; i++){
prime[i] = true;
}
long count = 0;
//Runs through main Sieve algorithm
for (long x = 2*2; x <= (b); x += 2 ){
prime[x] = false;
}
for (long x = 3; x <= sqrt(b); x = 2*x ){
if (prime[x] == true){
for (long y = pow(x,2); y <= b; y += x){
prime[y] = false;
}
}
}
//Loop to print out and count how many primes are present
for (long x = a; x <= b; x++){
if(prime[x] == true){
count++;
}
}
return count;
}
int main(){
int a, b;
cout << "Please enter two numbers separated by one space" << endl;
cin >> a >> b;
cout << Sieve(1,20) << endl;
cout << Sieve(a,b) << endl;
}
【问题讨论】:
-
在访问不允许访问的内存并且不是由于运行时间过长时会发生分段错误。
-
你能发布错误吗?
-
您似乎在这里缺少一个功能:
for (long x = 2*2; x <= (b); x += 2 )。这将导致x == b出现分段错误。
标签: c++ algorithm optimization sieve-of-eratosthenes