Here is a slight improvement to your procedure, while keeping the same algorithm for testing primality:
- Set the
sum
variable to the sum of the first two primes (i.e., 2+3 = 5)
- Start from 5, and test only numbers that are adjacent to multiples of 6
- For each number, test it only with divisors that are adjacent to multiples of 6
- For each number, test it only with divisors between 5 and the square root of the number
Please note that this implementation improves the performance of the algorithm but not the time-complexity of the algorithm, and that there are more efficient methods for testing primality.
int i, j, iplus, jplus, flag, iroot, sum = 2+3;
int iroot = (int)ceil(sqrt((float)5));
int square = iroot*iroot;
for (i=5, iplus=2; i<2000000; i+=iplus, iplus=4-iplus)
{
flag = 0;
if (square < i)
{
iroot++;
square = iroot*iroot;
// instead of calculating the square root of the number every time,
// calculate it at the beginning, and increment it only when needed
}
for (j=5, jplus=2; j<=iroot; j+=jplus, jplus=4-jplus)
{
if (i%j == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
sum += i;
}
printf("%i", sum);