Project Euler Problem 7: Solution in C++

/*

10001st prime

*/

#include <iostream>
#include <cmath>

using namespace std;

bool isPrime( long num )
{
switch( num )
{
case 1:
case 4:
case 6:
case 8:
case 9:
return false;
break;
case 2:
case 3:
case 5:
case 7:
return true;
break;
}
if( num % 2 == 0 || num % 3 == 0 )
return false;
long sq_root_of_num = floor( sqrt(num) );
long i = 5;
while( i <= sq_root_of_num )
{
if( num % i == 0 || num % (i+2) == 0 )
{
return false;
}
i += 6;
}

// num is prime
return true;
}

int main()
{
long num = 3;
int index = 1;

while( index < 10001 )
{
if( isPrime( num ) )
{
index++;
}
num += 2;
}
num -= 2;
cout << num << endl;
}

// ANSWER is 404743

Published by

Sreejith

A strong believer of: 1. Knowledge is power 2. Progress comes from proper application of knowledge 3. Reverent attains wisdom 4. For one's own salvation, and for the welfare of the world

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s