C++中素数的总和

acc*_*aze -1 c++ primes

嗨,伙计们,我正在制定一项计划,将所有素数的总和低于200万.这就是我所拥有的...我知道这个方法适用于寻找素数,因为我之前已经使用过它...但是当我运行这个程序时,我不断得到一个无限循环而没有输出......任何帮助都会很大不胜感激!

#include <iostream>
using namespace std;

int main (int argc, char * const argv[]) {
    bool isPrime=true;
    int i = 2;
    int sum = 0;
    do{

        for ( int j = 2; j < i; j++)
        {
            if ( i % j == 0 )
            {
                isPrime=false;
                break;
            }
        }
        if (isPrime)
        {
            cout << "Prime: " << i << endl;
            sum += i; // add prime number to sum
        }
        i++;

    }while(i < 2000000);

    cout << "the sum of all the primes below two million is: " << sum << endl;
    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 8

我能找到的唯一逻辑错误是你永远不会重新设置isPrimetrue循环内部,但这不应该导致无限循环,只是错误的结果.

我怀疑它是在无限循环中,我只是认为它需要很长时间,因为它是次优的.你不需要检查每个数字i,sqrt(i)甚至不需要检查i/2.

更好的是,你可以生成一个素数的筛子(谷歌这个),然后只需将它们加起来 - 这将更加高效.