欧拉计划:素数求和...为什么这行不通?

Project Euler: Summation of primes... Why won't this work?

本文关键字:为什么 行不通 求和 计划      更新时间:2023-10-16

我一直得到错误的答案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");

}

也许在您的平台上,长度不足以保存值。

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

在for循环中设置边界时,应该检查直到sqrt(p) + 1的数字。在计算平方根时可能会出现浮点错误(它可能会稍微低估它),因此有可能在循环中没有检查某些潜在因素。