The sum of prime numbers

I'm a novice C++ programmer. Recently I've been practicing using programming to solve problems at projecteuler.net. I am stuck on a particular problem that involves finding the sum of all prime numbers below 2,000,000. here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cmath>
using namespace std;
 
bool isPrime(int num)
{
if(num == 0)
return true;
 
     
for(int i = 2; i <= sqrt(num); i++)
{
        if(num % i == 0)
        {
                return false;
        }
}
        return true;
}
 
int main()
{
        unsigned int sum=2;
        for(int x=3;x<2000000;x+=2)
        {
                if (isPrime(x))
                {
                        sum += x;
                }
        }
        cout << sum;
        return 0;
}


The code runs fine, but is apparently outputting the wrong answer. I have checked my logic multiple times and feel it is correct (though I may be wrong.) So my conclusion now is that there is something in my code that isn't working the way I expect it to. Any help would be appreciated. Thanks :)
Last edited on
int is not wide enough to hold the sum and so it overflows. Use uint64_t instead.
Last edited on
Awesome, just changed it and worked like a charm. Thank you
This solution is pretty inefficient though... try using a prime number generation algorithm to get your numbers instead?

Also, 2 is a prime number :o
Topic archived. No new replies allowed.