# Thread: Trying to calculate the sum of all primes < 2M, fault in algorithm

1. ## Trying to calculate the sum of all primes < 2M, fault in algorithm

Can anybody see why the following piece of code does not provide the correct output for the calculation of the sum of all primes < 2 000 000?

Code:
#include <stdio.h>
#include <math.h>
int isPrime(int numb)
{
int i, stop = 0;
for (i = 2; !stop && i <= sqrt(numb); i++) {
if (numb % i == 0)
stop = 1;
}
if (!stop)
return 1;
else
return 0;
}

int main()
{
int i, sum = 2;
for (i = 3; i < 2000000; i += 2) {
if (isPrime(i)) {
printf("%i\n",i);
sum += i;
}
}
printf("%i\n", sum);
return 0;
}

2. What's the max value a signed integer type can store?

3. >What's the max value a signed integer type can store?
INT_MAX in limits.h

4. oh god thanks hahaha what a stupid mistake

5. A couple of issues:

1) isPrime doesn't handle 0 or 1 properly.
2) sqrt(numb) should really only be calculated once.

Oh, and just for fun...

Code:
int sumOfPrimesUpTo(int numb)
{
int sum = (numb * (numb + 1)) / 2;
for (int i = 0; i <= numb; ++i)
if (!isPrime(i))
sum -= i;
return sum;
}