Sunday, November 16, 2008

Problem #37

This one is kind of like the circular primes...quite simple really.


#include <iostream>
#include <string>
#include <cmath>

using namespace std;

bool isPrime (int);
int truncLeft (int);
int truncRight (int);
bool checkLeft (int);
bool checkRight (int);


int main()
{
int total = 0;

for (unsigned int i = 10; i < 1000000; i++)
if (isPrime (i))
if (checkLeft (i) == true && checkRight (i) == true)
total+=i;

cout << total << 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;
}

int truncLeft (int num)
{
char buffer[32];
string str, str2;

sprintf (buffer, "%i", num);
str = buffer;

str2 = str.substr (1);

return atoi (str2.c_str ());
}

int truncRight (int num)
{
char buffer[32];
string str, str2;

sprintf (buffer, "%i", num);
str = buffer;

str2 = str.substr (0, str.size () - 1);

return atoi (str2.c_str ());
}

bool checkLeft (int num)
{
while (num > 10)
{
num = truncLeft (num);
if (!isPrime (num))
return false;
}
return true;
}

bool checkRight (int num)
{
while (num > 10)
{
num = truncRight (num);
if (!isPrime (num))
return false;
}
return true;
}

No comments: