欧拉计划:素数求和...为什么这行不通?
Project Euler: Summation of primes... Why won't this work?
我一直得到错误的答案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的数字。在计算平方根时可能会出现浮点错误(它可能会稍微低估它),因此有可能在循环中没有检查某些潜在因素。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么会发生堆损坏
- 为什么使用 "this" 指针调用派生成员函数?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么比较运算符如此快速
- 为什么 Serial.println(<char[]>);返回随机字符?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 为什么不;名字在地图上是按顺序排列的吗
- 我的字符计数代码计算错误.为什么
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么这个说法行不通
- 为什么这行不通?第二个函数无法注册?
- C++模板有问题(大惊喜!为什么这行不通?
- 为什么选择普查尔('\\\');行不通
- 为什么这行不通?C++
- 欧拉计划:素数求和...为什么这行不通?