/*
* Problem 4
* 16 November 2001
*
* A palindromic number reads the same both ways. The largest palindrome made
* from the product of two 2-digit numbers is 9009 = 91 × 99.
*
* Find the largest palindrome made from the product of two 3-digit numbers.
*/
public class PE0004
{
public static void main(String[] args)
{
long largestPalindrome = 0;
for (int i = 100; i < 1000; i++)
{
for (int j = 100; j < 1000; j++)
{
largestPalindrome = (isPalindrome(i, j) > largestPalindrome) ? i * j : largestPalindrome;
}
}
System.out.println(largestPalindrome);
}
private static long isPalindrome(int i, int j)
{
boolean isAPalindrome = false;
String potentialPalindrome = i * j + "";
int length = potentialPalindrome.length();
for (int k = 0; k < length / 2; k++)
{
if (potentialPalindrome.charAt(k) == potentialPalindrome.charAt(length - k - 1))
{
isAPalindrome = true;
}
else
{
isAPalindrome = false;
return 0l;
}
}
if (isAPalindrome)
{
return i * j;
}
return 0l;
}
}
Sunday, September 13, 2009
Project Euler Problem 4
Rather than figuring out how to do looping and conditional statements in Mathematica, I just used Java for this one. I got the answer right on the first try, but did not try to optimize my code, so it's a bit clunky. The most difficult part of this problem was to do some string manipulation to determine whether the product was a palindromic number.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment