Sometimes, we want to find the largest palindrome made from the product of two 3-digit numbers with JavaScript.
In this article, we’ll look at how to find the largest palindrome made from the product of two 3-digit numbers with JavaScript.
How to find the largest palindrome made from the product of two 3-digit numbers with JavaScript?
To find the largest palindrome made from the product of two 3-digit numbers with JavaScript, we can loop through from 999 to 100 to find the products that create palindromes with another 3 digit number.
For instance, we write:
const isPalin = (i) => {
return i.toString() === i.toString().split("").reverse().join("");
}
const largestPalindrome = () => {
const arr = [];
for (let i = 999; i > 100; i--) {
for (let j = 999; j > 100; j--) {
const mul = j * i;
if (isPalin(mul)) {
arr.push(j * i);
}
}
}
return Math.max(...arr);
}
console.log(largestPalindrome());
We create the isPalin
function to check if i
converted to a string is the same originally as if it has been reversed with reverse
.
Then we define the largestPalindrome
function that has a nested loop to find the products between j
and i
.
And we call isPalin
to check if the product is a palindrome.
And then we call Math.max
with the entries of arr
spread as arguments.
Therefore, we see 906609 logged.
Conclusion
To find the largest palindrome made from the product of two 3-digit numbers with JavaScript, we can loop through from 999 to 100 to find the products that create palindromes with another 3 digit number.