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
1999990119909890100i%11≠0 → test j multiples of 11
2999990119799780210not palindrome
3999990119689670320continue
4998990119909880200new i; still multiples of 11 for j
5997990119909870300continue
6996990119909860400continue
7995990119909850500continue
8994990119909840600continue
9993990119909830700start i=993
10993990119799721470not palindrome
11993990119689612240not palindrome
12993990119579503010not palindrome
13993990119469393780not palindrome
14993990119359284550not palindrome
15993990119249175320not palindrome
1699399011913906609906609palindrome found → best = 906609 (993×913)

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