Bob Smith
Bob Smith

Reputation: 49

Project Euler #4

The objective is to find the greatest number that is a product of two three digit numbers and is a palindrome. I have written the following code in java, but when I run it, I get no output. What could be wrong?

public class Problem4{
    public static void main(String[] args){
        int reversedProduct=0;
        int temp=0;
        int product;
        for (int a=100; a<1000; ++a){
            for (int b=100; b<1000; ++b){
                product=a*b;
                while (product>0){
                    temp = product%10;
                    reversedProduct=reversedProduct*10+temp;
                    product=product/10;
                } if (reversedProduct==product){
                    System.out.println(product);
                }
            }
        }
    }
}

Upvotes: 4

Views: 369

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

You are zeroing out product in the process of reversing it. You should make a copy, and compare the reversed product to it.

int orig = product;
while (product>0){
    temp = product%10;
    reversedProduct=reversedProduct*10+temp;
    product=product/10;
}
if (reversedProduct==orig){
    System.out.println(reversedProduct);
}

Note that at this point your solution would print all palindromes, not just the lagrest one. Getting the largest one should be trivial, though.

Upvotes: 5

Related Questions