Project Euler Problem 7

December 15, 2011

I mentioned yesterday, I’ve been doing the first few problems of Project Euler and figured I’d share my solution to problem 7 here.

The Problem
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10,001st prime number?

The Solution
Let’s define a function isPrime(num) (granted, could be more efficient) and loop through the natural numbers, counting those that are prime.

/**
 * Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
 **/
#include
using namespace std;

bool isPrime ( unsigned long num ) {
        for(int i = num - 1; i > 1; i--) {
                if(num % i == 0) {
                        return false;
                }
        }
        return true;
}

int main () {
        unsigned long num = 2, primeCount = 0;

        while ( primeCount < 10001 ) {
                if ( isPrime (num) ) {
                        primeCount++;
                        cout << "Prime " << primeCount << " " << num << " is prime" << endl;
                }
                num++;
        }

        return(0);
}

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive