HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinorCanonical

Project Euler #4: Largest palindrome product

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
productlargestpalindromeprojecteuler

Problem

How can I make my code for Project Euler #4 more efficient and cleaner?

Project Euler #4: Largest palindrome product:


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 LargestPalindromeProduct {
    public static void main(String[] args) {

        int product = 0;
        int largest = 0;
        for (int first = 1; first  largest) {
                        largest = product;

                    }                   
                }

            }
        }
        System.out.println(largest);    
    }
}

Solution

For increased performance I think it might make sense to enhance your loop:

  • Start with 999 each and count downwards, as the largest product will most likely involve bigger numbers. This allows you to implement a strategy for pruning and return earlier (see other answers and comments for details).



  • Count only in the range of 100-999, since 1-99 aren't 3-digit numbers.



For a cleaner code you should refactor your if clause into a separate method. Something like

private boolean isPalindrome(int product) {
    return ((product / 100000) % 10 == product % 10
         && (product / 10000) % 10 == (product / 10) % 10
         && (product / 1000) % 10 == (product / 100) % 10);
}


A cleaner code would for me also involve consistent formatting and use of brackets, e.g.

  • (product / 100000) % 10 vs product / 10000 % 10



  • for (int first = 1 vs for(int second = 1

Code Snippets

private boolean isPalindrome(int product) {
    return ((product / 100000) % 10 == product % 10
         && (product / 10000) % 10 == (product / 10) % 10
         && (product / 1000) % 10 == (product / 100) % 10);
}

Context

StackExchange Code Review Q#134116, answer score: 7

Revisions (0)

No revisions yet.