This was a problem posted to reddit from a job application's website. The goal was to find the first 7 digit number from within Pi that was both a prime number and a palindrome. It's a fun little problem, but I cheated a bit by loading a pre-calculated value of Pi into memory first.
// we can use a (relatively) slow algorithm for prime checking because it's only
// checking when a palindrome appears
public static Boolean isPrime(int n)
{
for (int divisor = 2; divisor <= (Math.Sqrt(n)); divisor++)
if ((n % divisor) == 0) return false;
return true;
}
public static int reverse(int n)
{
int result = 0;
while ((n / 10) > 0) // break once n has only one digit
{
// shift the result one decimal place left, add the last digit from n
// the result of n % 10 is always the same as the last digit of n
result = (result * 10) + (n % 10);
n /= 10;
}
result = (result * 10) + (n % 10); // take the final digit
return result;
}
public static Boolean isPalindrome(int n)
{
if (reverse(n) == n)
return true;
return false;
}