X Tutup
Skip to content

Commit 365c847

Browse files
authored
Merge pull request TheAlgorithms#514 from Abhi13027/master
feat: Added Solution to Euler Problem 4
2 parents 6c2f83b + c49ca84 commit 365c847

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Project-Euler/Problem4.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// https://projecteuler.net/problem=4
2+
/* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
3+
Find the largest palindrome made from the product of two 3-digit numbers.
4+
*/
5+
const largestPalindromic = (digits) => {
6+
let i
7+
let n
8+
let m
9+
let d
10+
let limit
11+
let number = 0
12+
13+
for (i = 1; i < digits; i++) {
14+
number = 10 * number + 9
15+
}
16+
const inf = number // highest (digits - 1) number, in this example highest 2 digit number
17+
const sup = 10 * number + 9 // highest (digits) number, in this example highest 3 digit number
18+
19+
const isPalindromic = (n) => {
20+
let p = 0
21+
const q = n
22+
let r
23+
while (n > 0) {
24+
r = n % 10
25+
p = 10 * p + r
26+
n = Math.floor(n / 10)
27+
}
28+
return p === q // returning whether the number is palindromic or not
29+
}
30+
31+
for (n = sup * sup, m = inf * inf; n > m; n--) {
32+
if (isPalindromic(n)) {
33+
limit = Math.ceil(Math.sqrt(n))
34+
d = sup
35+
while (d >= limit) {
36+
if (n % d === 0 && n / d > inf) {
37+
return n
38+
}
39+
d -= 1
40+
}
41+
}
42+
}
43+
return NaN // returning not a number, if any such case arise
44+
}
45+
46+
console.log(largestPalindromic(3))

0 commit comments

Comments
 (0)
X Tutup