Problem 4: Largest Palindrome Product

A palindromic number reads the same forward and backward. For two-digit factors the maximum example is , showcasing how symmetry appears in multiplication.

For a general digit length , we examine factor pairs between and to locate the greatest palindromic product.

How to Solve

Descend from to . For each outer value, walk downward and exit early whenever because no larger palindrome can appear for this .

Every even-length palindrome is divisible by , so if is not a multiple we only test values that are. This reduces the inner loop dramatically without missing any candidates.

Iterate down to to avoid duplicate pairs. The first time reads the same forwards and backwards, update the best answer, capture the factors, and break the inner loop before continuing.

Code Solution


function largestPalindromeProduct(n) {
  const hi = Math.pow(10, n) - 1;
  const lo = Math.pow(10, n - 1);
  let best = 0;

  for (let i = hi; i >= lo; i--) {
    if (i * hi <= best) break;

    let jStart, jStep;
    if (i % 11 === 0) {
      jStart = hi;
      jStep = 1;
    } else {
      jStart = hi - (hi % 11);
      jStep = 11;
    }

    for (let j = jStart; j >= i; j -= jStep) {
      const prod = i * j;
      if (prod <= best) break;

      const s = String(prod);
      if (s === s.split("").reverse().join("")) {
        best = prod;
        break;
      }
    }
  }
  return best;
}

Test the Solution

Interaction Example (static) — n = 3

StepijStartjStepjprod = i·jisPalindromebestComments
199999011990989010❌0i%11≠0 → test j multiples of 11
299999011979978021❌0not palindrome
399999011968967032❌0continue
499899011990988020❌0new i; still multiples of 11 for j
599799011990987030❌0continue
699699011990986040❌0continue
799599011990985050❌0continue
899499011990984060❌0continue
999399011990983070❌0start i=993
1099399011979972147❌0not palindrome
1199399011968961224❌0not palindrome
1299399011957950301❌0not palindrome
1399399011946939378❌0not palindrome
1499399011935928455❌0not palindrome
1599399011924917532❌0not palindrome
1699399011913906609✅906609palindrome found → best = 906609 (993×913)

✅ For n = 3 the first palindrome hit shown here is 906609 from i = 993 and j = 913.