应用程序崩溃试图找到低于2,000,000的所有素数的总和

时间:2017-12-22 02:51:21

标签: c++ math primes

我试图从Project Euler解决问题10,其中包括找到低于2,000,000的所有素数之和。我开发了一个代码来做它但是当我运行它时,Windows说应用程序停止工作,然后我得到: " 3.442秒后退出流程,返回值为3221225725"

我不知道是否存在数学错误,逻辑错误或两者兼而有之。

这是代码(C ++):

#include<iostream>
using namespace std;

int main(){

    int vector[1999999];
    long sum = 0;

    for (int i = 0; i<=2000000; i++){ //stores all numbers from 2 to 2,000,000 on the vector
        vector[i] = i+2;
    }

    for (int i = 0; i<1999999; i++){ //choose a value
        for( int j = i+1; j<1999999; j++){//if there's any multiple of that value in a positon j, vector[j]=0
            if(vector[j]%vector[i]==0){
                vector[j] = 0;
            }
        }
    }//after this routine ends the vector stores only prime numbers and zeros

    for(int i = 0; i<1999999; i++){ //sum all values from the vector
        sum = sum + vector[i];
    }

    cout << sum << endl;

    return 0;
}

2 个答案:

答案 0 :(得分:0)

如果你坚持存储这么多的值,那么在堆中动态分配内存会更好:

int * vec = new int[2000000];

如果您不再需要这些值,请释放您分配的内存,如:

delete [] vec;

但是您的算法有很多优化,例如Sieve of Eratosthenes

最好不要使用vector作为数组的名称,因为vector是C ++ STL中的一种数据结构。

答案 1 :(得分:0)

感谢大家的回答,我用不同的方法解决了这个问题,没有使用任何数组。该程序非常慢(花了将近4分钟给我答案)但至少我终于得到了正确的答案,我将在稍后尝试改进它。

#include<iostream>
using namespace std;

int main(){
long long sum = 17;
int controle = 0;

for(int i = 2000000; i>8; i--){
    for(int j = 2; j<(i/2); j++){
        if(i%j==0){
            controle = 1;
            j = i/2;
        }
       }
    if(controle==0){
        sum = sum + i;
    }
    else{
        controle = 0;
    }
}

cout << sum << endl;

return 0;   
}