Number too big for int64_t?
Hi guys! I'm getting some troubles trying to find the sum of all primes below 1 million. I think I created a fairly good program (or at least one that should get the job done!), but apparently I'm having trouble with how I declare my variable/variables. This is the code:
Code:
/*The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below one million.*/
#include<stdio.h>
#include<stdint.h>
#include<math.h>
#define MAX 1000000
int isPrime(int64_t a);
int main(int argc[], char *argv[]) {
int64_t i;
uintmax_t sum=0;
for (i=2; i<MAX; i++) {
if (isPrime(i)==0) {
sum += i;
printf("%lld\t", sum);
printf("%lld\n", i);
}
}
printf("%lld", sum);
printf("Press a key to continue...\n");
getch();
return (0);
}
int isPrime(int64_t a) {
int64_t i;
if(a%2==0&& a!=2){
return(1);
}
for(i=2; i<a/2 ; i++) {
if(a%i==0) {
return(1);
}
}
return (0);
}
I tried to google some snippets of code, looking for variables and types capable of storing huge numbers, and uintmax_t and int64_t (both declared in stdint.h) were the biggest I found. Any way I can solve this or is this bruteforce method flawed?
edit: Oh yeah, I actually haven't said what's the problem! It compiles smoothly and start running (I guess the algorithm is correct, 'cause the program finds the correct sums up to small numbers, so it should do so for big ones too); around 250k, anyway, the sum reaches I don't know exactly what value, goes negative and start to decrement (that is, to augment...) Around 500k it reaches 0 again and starts to climb up again. Here I usually stop, 'cause I believe this shouldn't definitely be the right behavior...suggestions?