hey so I'm working on solving all of the Project Euler problems and I'm stuck at 10. My code keeps giving me a number that's close, but i think I'm off by about 2 million. Can anyone help?
Question: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
#include <stdio.h>
#include <math.h>
#define false 0
#define true 1
typedefintbool;
bool isPrime(double x);
int main(void)
{
int i, abc;
double sum = 0;
double x; // number to be checked for primeness
for (x = 2; x < 2000000; x++)
{
if (isPrime(x))
{
sum += x;
printf("%.0lf\n", sum);
}
}
return 0;
}
bool isPrime(double x)
{
if ((x != 2) && ((long)x % 2 == 0) || (x == 9)) // for numbers less than 10
returnfalse;
else
{
long i;
for (i = sqrt(x) - 1; i > 1; i--) // checks if sqrt(x) - 1 is divisible by any number from 2 to sqrt(x) - 1
{
if ((long)x % i == 0)
returnfalse;
}
returntrue;
}
}
BTW this is written in C, not C++... sorry about that...
Rather than cast between long/double all over the place... why not just use long everywhere? You avoid rounding errors which might be causing some minor goof ups.