-2
2000000以下所有素数的总和是多少?低于10总和 实施例是2 + 3 + 5 + 7 = 17欧拉项目10练习
我写这个代码,但仍然得到错误的答案: 我测试超过几百较低的数字,它已示出的正确答案。
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime(long n)
{
if (n < 2)
return false;
if (n == 2)
return true;
if (n == 3)
return true;
int k = 3;
int z = (int)(sqrt(n) + 1); // square root the n, because one of the product must be lower than 6, if squared root of 36
if (n % 2 == 0)
return false;
while (n % k != 0)
{
k += 2;
if (k >= z)
return true;
}
return false;
}
long primeSumBelow(long x)
{
long long total = 0;
for (int i = 0; i < x; i++) // looping for times of prime appearing
{
if (isPrime(i) == true)
total += i;
if (isPrime(i) == false)
total += 0;
}
cout << "fd" << endl;
return total;
}
int main()
{
cout << primeSumBelow(20) << endl;
cout << primeSumBelow(2000000) << endl;
system("pause");
return 0;
}
我想你只是忘记了求和函数的返回类型中的“long” - 总和比适合于有符号32位整数的值大60倍,并且你的局部变量具有不同的类型。 – molbdnilo