Skip to content

Instantly share code, notes, and snippets.

@belichuk
Created May 16, 2018 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belichuk/774e74d2c83c21e369fed0a4dfdf2486 to your computer and use it in GitHub Desktop.
Save belichuk/774e74d2c83c21e369fed0a4dfdf2486 to your computer and use it in GitHub Desktop.
Find all palindromes made from the product of two 4-digit numbers
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());
@belichuk
Copy link
Author

Intel Core I5-4300M CPU, 16 GB RAM

real    0m1.657s
user    0m0.000s
sys     0m0.078s

@belichuk
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment