Sum of prime numbers less than 2 million
I am trying to solve a Project Euler problem, it wants me to find the sum
of prime numbers below 2 million. Here is the code I wrote :
#include <iostream>
using namespace std;
bool isPrime (int x)
{
for(int i = 2; i < x; i++)
{
if(x % i == 0)
return false;
}
return true;
}
int main ()
{
int x = 0;
for(int i = 3 ; i < 2000000;i++)
{
if(isPrime(i))
x = x + i;
}
cout<<x+2<<endl;
}
I know this is not an efficient way to solve this problem. I found an
easier way but I think this solution should give the correct answer too.
The answer this code finds is : 1179908154. Can you tell me why this code
is giving the wrong answer?
No comments:
Post a Comment