Skip to content

Instantly share code, notes, and snippets.

@gauthierm
Last active November 9, 2021 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gauthierm/a336a9fd0615f68c2d3786f6f65802d0 to your computer and use it in GitHub Desktop.
Save gauthierm/a336a9fd0615f68c2d3786f6f65802d0 to your computer and use it in GitHub Desktop.
function getDigitAt(position, value) {
return Math.floor((value % 10 ** position) / 10 ** (position - 1));
}
function getLength(value) {
return Math.floor(Math.log10(value)) + 1;
}
function isPalindrome(value) {
const digits = getLength(value);
const halfDigits = Math.floor(digits / 2);
for (let i = 0; i < halfDigits; i++) {
if (getDigitAt(i + 1, value) !== getDigitAt(digits - i, value)) {
return false;
}
}
return true;
}
function getLargestPalindrome(digits1, digits2) {
const max1 = 10 ** digits1 - 1;
const max2 = 10 ** digits2 - 1;
const min1 = 10 ** (digits1 - 1) - 1;
const min2 = 10 ** (digits2 - 1) - 1;
let largest = 0;
for (let i = max1; i > min1; i--) {
for (let j = max2; j > min2; j--) {
const sum = i * j;
if (sum > largest && isPalindrome(sum)) {
largest = sum;
}
}
}
return largest;
}
getLargestPalindrome(3, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment