🍻


Project-Euler / 4

Problem 4 asks:

Find the largest palindrome made from the product of two 3-digit numbers.

I solved this with a simple brute force solution in Java:

public class Problem4 {
    public static void main(String[] args) {
        int product, rProduct, temp;
        int result = 0;
        for (int a = 100; a < 1000; a++) {
            // start from `a' to avoid duplicates
            for (int b = a; b < 1000; b++) {
                product = a * b;
                temp = product;
                rProduct = 0;
                while (temp > 0) {
                    rProduct = rProduct * 10 + temp % 10;
                    temp = temp / 10;
                }
                if (product == rProduct && product > result) {
                    result = product;
                }
            }
        }
        System.out.println(result);
    }
}

I would try to come up with a more efficient solution if the numbers were bigger, but as is it runs in under a tenth of a second.

Last updated on .