I was solving problem 4 of ProjectEuler:
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.
I couldn't get it right. This is my code:
public static long reverseNumber(long number){
long reversed = 0;
while(number != 0) {
long digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
return reversed;
}
long sum,finalSum=1,revSum;
for (int i=100;i<1000;i++){
for (int j=100;j<1000;j++){
sum=i*j;
revSum=reverseNumber(sum);
if (sum==revSum){
finalSum=sum;
}
}
}
System.out.println(finalSum);
This is some code I found online and it worked perfectly:
int maxPalin = -1;
for (int i = 100; i < 1000; i++) {
for (int j = 100; j < 1000; j++) {
int prod = i * j;
if (prod > maxPalin){
if (reverseNumber(prod)>maxPalin) {
maxPalin = prod;
}
}
}
}
System.out.println(Integer.toString(maxPalin));
But what's wrong with mine?
The goal is to find the max palindrome which is a product of two numbers between 100 and 999. The issue with your code is that you assume that last palindrome found would be the largest. This assumption is wrong.
For each palindrome you find, you should check if it's larger than the last palindrome you found before choosing it as a candidate for being the max palindrome.
BTW, the second snippet you posted is also incorrect, since it doesn't actually check that the current product is a palindrome (i.e. that prod==reverseNumber(prod)
).
A correct implementation would be:
public static void maxp () {
int maxPalin = -1;
for (int i = 100; i < 1000; i++) {
for (int j = 100; j < 1000; j++) {
int prod = i * j;
if (reverseNumber(prod) == prod && prod > maxPalin) {
maxPalin = prod;
}
}
}
System.out.println(maxPalin);
}
Your code returns a palindrome that isn't the max palindrome (the product of 995 and 583) :
580085
The second snippet returns a number that isn't a palindrome at all:
980099
The correct answer is the product of 913 and 993:
906609
Your implementation didn't find it because you overwrote it with a palindrome found in a later iteration, that was a product of a higher i
with a smaller j
.