-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path004.js
55 lines (41 loc) · 1.03 KB
/
004.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Largest Palindrome Product
* https://projecteuler.net/problem=4
* Computes largest palindrome made from the product of two 3-digit numbers
*
* Ashen Gunaratne
* mail@ashenm.ml
*
*/
/**
* @function palindrome
* @summary Computes largest palindrome
* @args {Number} digits - The number of digit per multiplier
* @description Returns the largest palindrome composed from two numbers of parameterized digits
*/
const palindrome = function computeLargestPalindrome(digits = 1) {
let m, x, y;
let ceil = '9'.repeat(digits);
let boundary = +'9'.padEnd(digits, '0');
const floor = +ceil.slice(1);
x = y = +ceil;
while (x !== floor) {
m = String(x * y);
if (m.split('').reverse().join('') === m) {
return +m;
}
if ((y -= 1) === boundary) {
x -= 1;
y = ceil;
}
if (x === boundary) {
ceil = boundary;
boundary -= 100;
}
}
return -1;
};
// tests
console.assert(palindrome(2) === 9009, `expected 9009 got ${palindrome(2)}`);
// answer
console.log(palindrome(3));