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;
break;
}
}
}
}
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();
}

### Like this:

Like Loading...

*Related*

Pingback: Project Euler problem 4 | code and effect