JavaScript Implementation of Problem 4

View source code here on GitHub!

p0004()

Project Euler Problem 4

I couldn't figure out how to do this as efficiently as I would have liked. I am SURE that there is a better way to check if a number is a palindrome, but I could not think of one.

Problem:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Returns:

number --

 1/**
 2 * Project Euler Problem 4
 3 *
 4 * I couldn't figure out how to do this as efficiently as I would have liked. I am
 5 * SURE that there is a better way to check if a number is a palindrome, but I
 6 * could not think of one.
 7 *
 8 * Problem:
 9 *
10 * A palindromic number reads the same both ways. The largest palindrome made from
11 * the product of two 2-digit numbers is 9009 = 91 × 99.
12 *
13 * Find the largest palindrome made from the product of two 3-digit numbers.
14 *
15 * @return {number}
16 **/
17exports.p0004 = function() {
18    let answer = 0;
19    for (let v = 101; v < 1000; v++) {
20        for (let u = 100; u < v; u++) {
21            const p = u * v.toString();
22            const ps = p.toString();
23            if (ps === ps.split('').reverse().join('') && p > answer) {
24                answer = p;
25            }
26        }
27    }
28    return answer;
29};

Tags: palindrome