Problem statement

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.

Thoughts

I think this just needs a brute-force approach. I did find this interesting formula on Quora while searching for alternatives, but it makes the solution pretty complicated, and I think it may even take longer than the brute force approach.

Solution

Prime sieve up to 2 million, sum all the found primes on the way.

#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#define LIMIT 2000000

bool primes[LIMIT];

int main()
{
	/* Assume every integer is prime until we know otherwise */
	for (int i = 0; i < LIMIT; ++i) {
		primes[i] = true;
	}

	primes[0] = false; /* 0 is not a prime */
	primes[1] = false; /* 1 is not a prime */

	double sum = 0;
	for (int i = 2; i < LIMIT + 1; ++i) {
		if (primes[i]) {
			sum += i;
			for (int j = i + i; j < LIMIT; j += i) {
				primes[j] = false;
			}
		}
	}

	printf("%f", sum);
}