【问题标题】:App crash trying to find de sum of all primes below 2,000,000应用程序崩溃试图找到低于 2,000,000 的所有素数的总和
【发布时间】:2017-12-22 02:51:20
【问题描述】:

我试图解决 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;
}

【问题讨论】:

  • int vector[1999999]; 很可能比你的堆栈大。
  • for (int i = 0; i&lt;=2000000; i++){ 将导致边界访问。 1999998 是您可以在数组中访问的最高索引。
  • 查看埃拉托色尼筛及其各种改进。比这段代码快很多倍。
  • 关于如何存储这么多值的任何提示?并感谢您的回答
  • 另一个提示:如果你使用 Eratosthenes 筛,你可以用std::vector&lt;bool&gt; 替换你的整数数组,它有一个更节省空间的实现。正如已经提到的,它会比你的代码运行得更快。

标签: c++ math primes


【解决方案1】:

如果你坚持存储这么多值,最好在堆中动态分配内存,例如:

int * vec = new int[2000000];

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

delete [] vec;

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

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

【讨论】:

    【解决方案2】:

    感谢大家的回答,我用不同的方法解决了这个问题,没有使用任何数组。程序很慢(花了将近 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;   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多