|
| 1 | +// problem004.js |
| 2 | + |
| 3 | +// A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. |
| 4 | + |
| 5 | +// Find the largest palindrome made from the product of two 3-digit numbers. |
| 6 | + |
| 7 | +/////////////////////////////////////////////////////////////////////////////// |
| 8 | +// NOTES ABOUT THE SOLUTION: |
| 9 | +// This solution cycles to test all pairs of factors between 111 and 999 that meet the condition of generating a palindrome and saves the largest found. |
| 10 | +// I think there must be another optimal solution to avoid testing all cases |
| 11 | +// cutting the loop around the largest factor pair |
| 12 | +// That's why I thought about doing the loop from highest to lowest. |
| 13 | +/////////////////////////////////////////////////////////////////////////////// |
| 14 | + |
| 15 | +let bottom = 111 |
| 16 | +let top = 999 |
| 17 | + |
| 18 | +function isPalindrome(n) { |
| 19 | + // console.log(`${ n.toString().split("").reverse().join("") }`); |
| 20 | + // console.log(`${ n.toString()}`) ; |
| 21 | + |
| 22 | + return n.toString().split("").reverse().join("") === n.toString(); |
| 23 | +} |
| 24 | + |
| 25 | +// Test isPalindrome condition |
| 26 | +// console.log(isPalindrome('1000')); |
| 27 | +// console.log(isPalindrome('1001')); |
| 28 | +// console.log(isPalindrome('3443')); |
| 29 | +// console.log(isPalindrome('3435')); |
| 30 | + |
| 31 | + |
| 32 | +let i; |
| 33 | +let j; |
| 34 | +let foundi; |
| 35 | +let foundj; |
| 36 | +let foundPalindrome; |
| 37 | + |
| 38 | +// Find all cases |
| 39 | +i = top; |
| 40 | +do { |
| 41 | + |
| 42 | + j = top; |
| 43 | + do { |
| 44 | + |
| 45 | + if( isPalindrome( j * i ) ) |
| 46 | + { |
| 47 | + console.log(`FOUND: ${i} x ${j} = ${j * i} is Palindrome`); |
| 48 | + |
| 49 | + if(!foundPalindrome || (i*j) > foundPalindrome) |
| 50 | + { |
| 51 | + foundi = i; |
| 52 | + foundj = j; |
| 53 | + foundPalindrome = (i*j); |
| 54 | + } |
| 55 | + |
| 56 | + } else { |
| 57 | + // console.log(`FOUND: ${i} x ${j} = ${j * i} is NOT Palindrome`); |
| 58 | + } |
| 59 | + |
| 60 | + j--; |
| 61 | + } |
| 62 | + while ( j >= bottom /*&& !(found1 && found2)*/) |
| 63 | + |
| 64 | + |
| 65 | + i--; |
| 66 | +} |
| 67 | +while ( i >= bottom /* && !(found1 && found2) */ ) |
| 68 | + |
| 69 | +console.log(`Largest Palindrome => ${foundi} 𝗑 ${foundj} = ${foundPalindrome}`); |
0 commit comments