我正在尝试这个程序来查找所有素数低于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;
}
答案 0 :(得分:4)
d
永远都是假的。没有代码将其设置为true
。
此外,您需要以10(2 + 3 + 5)开始e
。
答案 1 :(得分:1)
试试这个:)
#include <iostream>
using namespace std;
int main(){
bool prime;
int num = 200000;
int sum = 0;
for (int i=3; i<=num; i++){
prime = true;
for(int j=2; j<=i/2; j++){
if(i%j == 0) prime = false;
}
if(prime) sum+=i;
}
cout << sum;
}
答案 2 :(得分:0)
在我看来,找到数字是素数的最有效方法是:
<=3
),然后是素数。假设只有正整数参与。用C ++语言:
bool IsPrime(unsigned int nCheck)
{
assert(nCheck>0);
if(nCheck<=3)
return true;
if(nCheck%2==0)
return false;
for(int nCounter = 3; nCounter <= sqrt(nCheck); nCounter += 2) // Skip evens
{
if(nCheck % nCounter == 0)
return false;
}
return true;
}
任何数字都是该数字的1到平方根。例如,100,可被10除尽。即使它被50整除,它也可被5整除。所以,只需从1到10进行检查。