Docs


Problem 10: Summation of primes

Problem

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

Find the sum of all the primes below two million.

Solution

/*
 * Summation of primes
 * Problem 10 <https://projecteuler.net/problem=10>
 *
 * Project Euler
 *
 * By Ankit R Gadiya
 */

#include <stdio.h>

long int largest_factor (long int num, int fact);

int main (void)
{
	long int num = 2, largest_fact;
	long long int sum = 0;

	while (num < 2000000) {
		largest_fact = largest_factor(num, 2);

		if (largest_fact == num)
			sum += num;

		num++;
	}

	printf("%lld\n", sum);

	return 0;
}

long int largest_factor (long int num, int fact)
{
	if (num == 1) {
		return fact;
	} else {
		while (fact * fact <= num) {
			if (num % fact == 0)
				return largest_factor (num / fact, fact);
			else
				fact++;
		}
		return num;
	}
}

prob10.c

Result

142913828922