Sunday 21 August 2016

Project Euler Problem 4: Largest palindrome product

Problem

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.

Solution

The efficiency of checking if a number is palindrome can certainly be improved, but I am more focused on optimization on two for loops.

  • Start from 999 backwards, and start j=i instead of 999
  • Check product > current largest palindrome first instead of checking product is palindrome first
  • break inner loop when we know the rest product cannot be larger than the current largest palindrome

      public static void main(String[] args) {  
           long largestPalindrome = 0;  
           for (int i = 999; i >= 100; i--){  
                for (int j = i; j >= 100; j--){  
                     long product = i * j;  
                     if (product > largestPalindrome){  
                          if (isPalindrome(product)){  
                               largestPalindrome = product;  
                               break;  
                          }  
                     }else{  
                          break;  
                     }  
                }  
           }  
           System.out.println(largestPalindrome);  
      }  
      private static boolean isPalindrome(long product) {  
           String s = String.valueOf(product);  
           return reverse(s).equals(s);  
      }  
      private static String reverse(String s) {  
           String r = "";  
           for (int i=s.length()-1; i>=0; i--){  
                r += s.charAt(i);  
           }  
           return r;  
      }  

No comments:

Post a Comment