I doing another question from the Eular problems page.
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
I’ve managed to write the code below but i think somewhere along the line (namely when we get to big prime numbers) the code loses accuracy. The answer should be 142913828922 but i get 1179908154.
I dont know why im not getting the answer because the code below works for under 10.
Any help would be great. the reason im doing these problems is to get better at C.
code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Initialise */
void CalcNumber(unsigned long number);
int isPrime(unsigned long number);
/* Functions*/
void CalcNumber(unsigned long number)
{
unsigned long i = 1;
unsigned long prime = 0;
while(i != number)
{
i++;
if(isPrime(i))
{
printf("prime: %lu\n", i);
prime += i;
}
}
printf("The sum of primes under %lu: %lu\n",number, prime);
printf("count: %d\n", i);
}
int isPrime(unsigned long number)
{
int i, nb, count, test,limit;
test = count = 0;
nb = number;
limit = sqrt(nb) + 1;
if(nb == 2)
{
return 1;
}
if (nb % 2 == 0)
test = 1;
else{
for (i = 3 ; i < limit && ! test; i+=2, count++)
if (nb % i == 0)
test = 1;
}
if (!test)
return 1;
else
return 0;
}
int main(void)
{
unsigned long number;
printf("Enter a number: \n");
scanf("%ul", &number );
CalcNumber(number);
return EXIT_SUCCESS;
}
Considering the length of the number you should use a data type long at least 64 bits. The newer C99 standard includes the
long long(andunsigned long long) datatype that is at least 64 bits. If you need toprintfthem you have to use"%lld"and"%llu".