Euler Problem 4

So continuing with the series of solving Euler presented problems, this shows Problem 4. Interesting I’ve teamed up with a former colleague on Twitter, @am_doherty, we’ve decided to tackle 1 a week. We’ll both post our solutions on a Friday, at about 3pm. It’ll be interesting to see different solutions that we come up with.

I chose Problem 4 this week, @am_doherty will choose the problem next week.

Euler Problem 4

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.

My Solution

At first I thought this solution would be incredibly slow, but after running it, it completes in less than a second and so seems good enough.

The main method is as follows:

int max = 0;
int param1 = 0;
int param2 = 0;
int jMin = 99;

for (int i = 999; i > 99; i--) {
  for (int j = 999; j > jMin; j--) {
    String result = Integer.toString(i * j);
    String reversed = reverseStr(result);

    if (result.equals(reversed)) {
      if (i * j > max) {
        param1 = i;
        param2 = j;
        jMin = j;
        max = i * j;

System.out.println("param1 = " + param1 + ", param2 = " + param2 + ", max = " + max);

I added in a few extra parameters to reduce the loop mechanism and whilst I think these made the program a little faster, the program still executed in under a second without them.

The reverseStr method is as follows. I’m certain there may be a faster way of doing this, but with the small strings involved it seemed good enough:

public static String reverseStr(String orgStr) {
  StringBuilder reverseStr = new StringBuilder();
  for (int i = orgStr.length(); i > 0; i--) {
    reverseStr.append(orgStr.charAt(i - 1));

  return reverseStr.toString();

One thought on “Euler Problem 4

  1. Pingback: Project Euler problem 4 | code and effect

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s