我正在尝试这个程序来查找所有素数低于200万的总和,但出于某种原因,我想出了一个远低于我应该预期的数字。总计2000000以下的素数
这是我的代码。一个合作工作表示,我可能不会用我的程序捕捉所有素数,但他不知道C++,我不明白我是如何错过它们的。
#include <iostream>
using namespace std;
int main()
{
int a = 500000;
int e = 0;
// this is an array to hold all the prime number i find,
// it's initialized to the arbitrarily high number of 500000
int list[a];
//here i am initializing the first members of my list to the first primes
list[0] = 2;
list[1] = 3;
list[2] = 5;
a = 3; // i set a = 3 to catch the next coming prime of 7
for (int c = 5; c < 2000000; c++)
{
// this bool is for prime catching,
// if d is false then the number will not be saved into the array
bool d = false;
// this bool is for an exit statement in the following iterative loop,
// if it's false the loop will exit
bool h = true;
for (int i = 0; list[i] < c/2 + 1 && h == true; i++)
{
// this checks to see if a number is evenly
// divisable by any of my primes so far
if (c % list[i] == 0)
{
d = false;
h = false;
}
}
if (d == true)
{
list[a] = c; // if i find a prime i save it into my array
e += c; // if i find a prime i sum it to my total
a++;
}
}
cout << e;
}
项目欧拉问题?查看[Eratosthenes的筛子](http://en.wikipedia.org/wiki/Sieve_of_eratosthenes)。它的速度非常快,可以达到一定的数值,我相信有1000万。 – Marlon 2013-03-22 15:57:04
@Marlom的确,问题10. – Rapptz 2013-03-22 15:58:51
看起来你正在做[Eratosthenes筛](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)困难的方式。 – 2013-03-22 15:59:34