Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:15
Show Gist options
  • Save dmnugent80/9c75f2a32b7e9aba1798 to your computer and use it in GitHub Desktop.
Save dmnugent80/9c75f2a32b7e9aba1798 to your computer and use it in GitHub Desktop.
Largest Palindrome Product of Two Three Digit Numbers
//Brute Force
public class LargestPalindrome
{
public static void main(String[] args)
{
MaxPalindrome myObject = new MaxPalindrome();
int maxPal = myObject.findLargestPalindromeThreeDigits();
System.out.println(String.format("Max Product: %-4d", maxPal));
}
}
public class MaxPalindrome
{
public int findLargestPalindromeThreeDigits(){
int max = 0;
for (int i = 999; i > 800; i--){
for (int j = i; j > 800; j--){
int prod = i * j;
if (isPalindrome(prod) && prod > max){
System.out.println(String.format("palindrome: %-4d, product of %-4d and %-4d", prod, i, j));
max = prod;
}
}
}
return max;
}
public boolean isPalindrome(int product){
String prod = Integer.toString(product);
if (prod.equals(new StringBuilder(prod).reverse().toString())){
return true;
}
return false;
}
}
/*output:
palindrome: 906609, product of 993 and 913
Max Product: 906609
*/
//Using Math
//http://stackoverflow.com/questions/7183977/find-the-largest-palindrome-made-from-the-product-of-two-3-digit-numbers
public class LargestPalindrome
{
public static void main(String[] args){
parent:
for(int i=9; i>0;i--){
for(int j=9; j>=0; j--){
for(int k=9; k>=0; k--){
int palindrome = i*100001+j*10010+k*1100;
int temp = (palindrome-(palindrome%1000))/1000+1;
for(int m = temp; m<Math.sqrt(palindrome);m++){
if(palindrome%m==0){
System.out.println("The biggest number is: "+palindrome);
System.out.println(palindrome+" = "+m+"*"+palindrome/m);
break parent;
}
}
}
}
}
}
}
/*output
The biggest number is: 906609
906609 = 913*993
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment