C++ solution to Project Euler Problem 10

Problem 10:

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

Find the sum of all the primes below two million.

Running time: ~5 secs

Assessment: This solution is in C++ for some reason. Oh well. Anyway, it works fine, but like most of my other early factorization solutions, it doesn’t memoize anything, which means lots of redundant work, which makes for very long execution times. It’s pretty bad all around.

#include <iostream>
#include <cmath>
 
using namespace std;
 
long long is_prime(long long n)
{
	//returns 0 if not prime, 1 if prime
	if (n % 2 == 0)
		return 0;
	for (long long i = 3; i <= (pow(n,0.5)); i += 2)
	{
		if (n % i == 0)
			return 0;
	}
	return 1;
}
 
int main()
{
	unsigned long long sum = 0;
 
	for (int i = 3; i < 2000000; i += 2)
	{
		if (is_prime(i))
		{
			sum += i;
		}
	}
 
	cout << sum + 2;
 
	return 0;
}

1 thought on “C++ solution to Project Euler Problem 10

Leave a Reply

Your email address will not be published. Required fields are marked *