Created
May 16, 2018 16:22
-
-
Save belichuk/774e74d2c83c21e369fed0a4dfdf2486 to your computer and use it in GitHub Desktop.
Find all palindromes made from the product of two 4-digit numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const reverseNum = s => String(s).split('').reverse().join(''); | |
const genPalindrome = (len) => { | |
const palindromes = new Set(); | |
const mod = len%2 !== 0; | |
const iLen = ~~(len/2); | |
const start = Math.pow(10, iLen - 1); | |
const end = Math.pow(10, iLen) - 1; | |
for (let i = end; i >= start; i--) | |
{ | |
if (mod) { | |
for (let j = 9; j>=0; j--) { | |
palindromes.add( Number(i + String(j) + reverseNum(i)) ); | |
} | |
} else { | |
palindromes.add( Number(i + reverseNum(i)) ); | |
} | |
} | |
return palindromes; | |
}; | |
const palindromes7 = genPalindrome(7); | |
const palindromes8 = genPalindrome(8); | |
const palindromes = new Set([...palindromes7, ...palindromes8]); | |
let res = ''; | |
for (let i = 9999; i > 1000; --i) { | |
if (i%10 === 0) continue; | |
for (let j = i, mult = i*j; j > 1000; --j, mult -= i) { | |
if (i%10 === j) continue; | |
if (palindromes.has(mult)) { | |
res += `${i} ${j} ${mult}\n`; | |
} | |
} | |
} | |
fs.writeFile('output.txt', res, () => process.exit()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Intel Core I5-4300M CPU, 16 GB RAM