我正在尝试这个程序来找到所有低于 200 万的素数的总和,但由于某种原因,我得出的数字远低于我的预期。
这是我的代码。一位同事说我可能无法用我的程序捕捉所有素数,但他不懂 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;
}