应用程序崩溃试图找到低于 2,000,000 的所有素数的总和
App crash trying to find de sum of all primes below 2,000,000
我正在尝试解决 Project Euler 中的第 10 题,其中包括找出所有小于 2,000,000 的素数之和。我开发了一个代码来做到这一点,但是当我 运行 它 windows 说应用程序停止工作然后我得到:
"Process exited after 3.442 seconds with return value 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;
}
如果你坚持存储这么多值,最好在堆中动态分配内存,如:
int * vec = new int[2000000];
如果您不再需要这些值,请像这样释放您分配的内存:
delete [] vec;
但是你的算法有很多优化,比如Sieve of Eratosthenes
数组名最好不要用vector
,因为vector
是C++ STL中的一种数据结构
谢谢大家的回答,我用不同的方法解决了这个问题,没有使用任何数组。程序很慢(花了将近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;
}
我正在尝试解决 Project Euler 中的第 10 题,其中包括找出所有小于 2,000,000 的素数之和。我开发了一个代码来做到这一点,但是当我 运行 它 windows 说应用程序停止工作然后我得到: "Process exited after 3.442 seconds with return value 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;
}
如果你坚持存储这么多值,最好在堆中动态分配内存,如:
int * vec = new int[2000000];
如果您不再需要这些值,请像这样释放您分配的内存:
delete [] vec;
但是你的算法有很多优化,比如Sieve of Eratosthenes
数组名最好不要用vector
,因为vector
是C++ STL中的一种数据结构
谢谢大家的回答,我用不同的方法解决了这个问题,没有使用任何数组。程序很慢(花了将近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;
}