Euler Problem 4: Largest palindrome product
Oct 15, 2017 16:50 · 227 words · 2 minutes read
Euler Problem 4
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.
The solution is to search for palindrome number starting from the largest number. We check if the product of two numbers is a palindrome and replace k with it if it’s larger than k. We return k, the largest palindrome, after the loops.
Solutions
Solution in R
is_palindrome <- function(x) {
s <- as.character(x)
s_reverse <- paste(rev(unlist(strsplit(s, ""))), collapse = "")
return(s == s_reverse)
}
n = 0
m = 0
k = 0
for (i in 999:100) {
for (j in 999:100) {
number <- i * j
if (is_palindrome(number) & number > k) {
n = i
m = j
k = number
}
}
}
paste(n, "x", m, "=", k)
## [1] "993 x 913 = 906609"
Solution in Python
def is_palindrome(x):
s = str(x)
return s == s[::-1]
n = 0
m = 0
k = 0
for i in range(999, 99, -1):
for j in range(999, 99, -1):
number = i * j
if is_palindrome(number) and number > k:
n = i
m = j
k = number
print("%d x %d = %d" %(n, m, k))
## 993 x 913 = 906609