0

我一直得到 1179908154 的错误答案。起初我将其归咎于我的求和变量是 int 类型,而不是 long。我给了它长类型,但我得到了相同的答案。想法?

// Project Euler

// Problem 10

#include <iostream>
#include <cmath>
using namespace std;

void main() 
{

int p = 3;
long sum = 2;
bool isPrime;
for (p; p < 2000000; p++)
{
    isPrime = true;

    for (int i = 2; i <= sqrt(static_cast<double>(p)); i++) // cast into double for sqrt function
    {
        if (p % i == 0)
        {
            isPrime = false;
            break;

        }
    }
    if (isPrime == true)
    {
        cout << p << endl; // show each prime
        sum += p; // add prime to sum 
    }

}
cout << sum << endl; // show sum 

system("pause");

}

4

3 回答 3

2

Maybe on your platform the long is not enough to hold the value too. Try a long long instead.

于 2013-04-28T01:07:49.003 回答
2

不要自己写素数生成器,真的不容易。只需使用这个http://cr.yp.to/primegen.html,对于 euler 项目来说已经足够了。

于 2013-09-24T08:31:48.730 回答
0

When putting the bounds on your for loop, you should check numbers up until sqrt(p) + 1. You can get floating point errors when calculating the square root (it might underestimate it slightly), so it's possible that some potential factors are not checked in the loop.

于 2013-04-28T01:04:45.410 回答