Sunday, November 16, 2008

Problem #41

This one was actually quite easy.


#include <iostream>
#include <string>
#include <ctime>
#include <cmath>
#include <algorithm>

using namespace std;

bool isPrime (int);

int main(void)
{
clock_t start = clock();
int total = 0;
string str;
int holder[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int holder2 = 0;

for (int j = 1; j <= 9; j++)
{
sort (holder, holder + j);

do {
str.clear();
for (unsigned int i = 0; i < j; i++)
str += holder[i] + '0';
holder2 = atoi (str.c_str());
if (isPrime (holder2))
if (holder2 > total)
total = holder2;
} while ( next_permutation (holder,holder+j) );
}


cout << total << endl
<< "Process took " << (static_cast<double> (clock()) - start) / CLOCKS_PER_SEC << " seconds." << endl;
system("pause");
return 0;
}

bool isPrime (int num)
{
if (num == 0 || num == 1)
return false;

if (num == 2 || num == 3)
return true;

for (unsigned int i = 2; i < static_cast<int> (sqrt (static_cast<double> (num))) + 1; i++)
if (num % i == 0)
return false;
return true;
}

No comments: