BiggestPalindrome

by

Once again, I cheated by using Mathematica instead of one of the two sanctioned computing environments (Python or Sage). To test whether or not a number was a palindrome, I used Mathematica’s built-in abilities to convert an expression into a string, and to reverse the characters in any given string. Here is my code (it is based on an algorithm I remember Eric describing last week):

Palindrome[x_] := (y = ToString[x]; y == StringReverse[y]);

BiggestPalindrome[n_] := (x = 1;
  For[i = 10^n - 1, i > 10^(n - 1) - 1, --i,
   For[j = i, j > 10^(n - 1) - 1, --j, m = i*j;
    If[Palindrome[m] && m >= x, x = m]]]; x)

Typing BiggestPalindrome[n] will give the largest palindrome that is the product of two n-digit numbers.It took Mathematica about 5.75 seconds to compute the solution when n=3. I asked Mathematica to give me the answer for n=4, but I got tired of waiting for it to finish.

I’m sure there must be a way to cut down on the number of loops to go through. If there is, I’m sure somebody else will produce it.

Tags: , ,

One Response to “BiggestPalindrome”

  1. NIck Brandaleone Says:

    I was able to get rid of the FOR loops entirely, by re-writing the answer in a more “functional” way, which is more in the spirit of LISP/Mathematica.

    That being said, it is about 5-10% slower than your solution on my computer. Most of the time seems to be in the “select” statement.

    PalindromeQ[x_] := (y = ToString[x]; y == StringReverse[y]);
    BiggestPalindrome[n_] :=
    Module[{m =
    KroneckerProduct[Range[10^(n – 1), 10^n – 1],
    Range[10^(n – 1), 10^n – 1]]},
    Max[Select[Flatten[m], PalindromeQ]]];
    BiggestPalindrome[3]

Leave a comment