Project Euler | Problem Four

Problem Four

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.

There doesn’t seem to be any easy way to do this mathematically so we will bruteforce. Starting at 999 x 999 and work all the way down. For every number we send it to the isPalidrome(…) function.

Because it breaks as soon as it finds that it doesn’t match the function should not be too heavy.

/**
 * 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.
 * @author syfran
 * @version %I% %U% %G%
 */
package com.syfran.Euler;                                                                                                      

public class ProblemFour extends AbstractEuler
{
        public static void main(String[] A)
        {
                ProblemFour p = new ProblemFour();

                p.start();
        }                 

        public long solve()
        {
                final long MAX = 999; // highest possible
                final long MIN = 100; // lowest possible
                long greatest = 0;
                for (long current = MAX; current > MIN; current--)
           {
                        for (long second = current; second > 0; second--)
                        {
                                long mult = current * second;
                                if (isPalidrome(mult) && mult > greatest)
                                        greatest = mult;
                        }
                }
                return greatest;
        }

        private boolean isPalidrome(long current)
        {

                String str = current + "";
                for (int i = 0; i < str.length() / 2; i++)
                {
                        if (str.charAt(i) != str.charAt(str.length() - 1 - i))
                                return false;
                }
                return true;

        }
}
Total RunTime: 289ms

This is longest one yet…

Possible Optimizations:

- Instead of keeping one at 999 and iterating the other, multiply in a way that makes it constantly decrease. This would be a huge improvement.


One Response to “Project Euler | Problem Four”

  • Stalker Says:

    Always make sure that both numbers are at most 1 digit away from each other. Decrement one, then decrement the other one, switch between them back and forth. So it would be

    999×999
    999×998
    998×998
    998×997

    etc…

    The very first occurrence of palindrome would be the answer.

    Even if all you can think of is brute-force, at least try not to make it a mindless brute-force, because that defeats the whole purpose of project Euler.

Leave a Reply