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
| Step | i | jStart | jStep | j | prod = i·j | isPalindrome | best | Comments |
|---|---|---|---|---|---|---|---|---|
| 1 | 999 | 990 | 11 | 990 | 989010 | ❌ | 0 | i%11≠0 → test j multiples of 11 |
| 2 | 999 | 990 | 11 | 979 | 978021 | ❌ | 0 | not palindrome |
| 3 | 999 | 990 | 11 | 968 | 967032 | ❌ | 0 | continue |
| 4 | 998 | 990 | 11 | 990 | 988020 | ❌ | 0 | new i; still multiples of 11 for j |
| 5 | 997 | 990 | 11 | 990 | 987030 | ❌ | 0 | continue |
| 6 | 996 | 990 | 11 | 990 | 986040 | ❌ | 0 | continue |
| 7 | 995 | 990 | 11 | 990 | 985050 | ❌ | 0 | continue |
| 8 | 994 | 990 | 11 | 990 | 984060 | ❌ | 0 | continue |
| 9 | 993 | 990 | 11 | 990 | 983070 | ❌ | 0 | start i=993 |
| 10 | 993 | 990 | 11 | 979 | 972147 | ❌ | 0 | not palindrome |
| 11 | 993 | 990 | 11 | 968 | 961224 | ❌ | 0 | not palindrome |
| 12 | 993 | 990 | 11 | 957 | 950301 | ❌ | 0 | not palindrome |
| 13 | 993 | 990 | 11 | 946 | 939378 | ❌ | 0 | not palindrome |
| 14 | 993 | 990 | 11 | 935 | 928455 | ❌ | 0 | not palindrome |
| 15 | 993 | 990 | 11 | 924 | 917532 | ❌ | 0 | not palindrome |
| 16 | 993 | 990 | 11 | 913 | 906609 | ✅ | 906609 | palindrome found → best = 906609 (993×913) |
✅ For n = 3 the first palindrome hit shown here is 906609 from i = 993 and j = 913.