Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@belichuk

belichuk May 16, 2018

Intel Core I5-4300M CPU, 16 GB RAM

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

belichuk commented May 16, 2018

Intel Core I5-4300M CPU, 16 GB RAM

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

This comment has been minimized.

Show comment
Hide comment
@realsba

This comment has been minimized.

Show comment
Hide comment
@realsba

This comment has been minimized.

Show comment
Hide comment
@belichuk

This comment has been minimized.

Show comment
Hide comment
Owner

belichuk commented Jun 11, 2018

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