Zachary Stence

Problem 10: Summation of primes

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

Find the sum of all the primes below two million.

I first solved this problem May 27th, 2015 in the summer after my junior year of highschool. I do not have the original var I wrote, but I have solved the problem again and included the code below.

To solve this problem I simply used the same isPrime function I had previously written, looped through every number below 2 million, and added it to a sum if it was prime. Very brute force, but it works.

#include <iostream>
#include <cmath>

bool isPrime(int x) {
  // 1 is not prime; false for non-positive integers
  if (x <= 1) return false;
  // 2 is prime
  else if (x == 2) return true;
  else if (x % 2 == 0) return false;
  else {
    // iterate through all odd nums less than square root of x
    for (int i = 3; i <= sqrt(x); i += 2)
      // if x is divisible by a number, it is not prime
      if (x % i == 0) return false;
    return true;
  }
}

int main() {
  long long sum = 0;
  for (int i = 0; i < 2000000; i++) {
    if (isPrime(i)) sum += i;
  }
  std::cout << sum << std::endl;
}

Answer: 142913828922