Project Euler in R Problem 4

The goal of this problem was to find the largest palindrome made from the product of two 3-digit numbers. I had a lot of fun with this one and the string splitting practice was very useful for future problems.

First, I created a function named is.pal which takes a number, converts it to a character, and splits it by digit into a vector. It then tests whether the vector is equivalent forward and reverse to determine if the original input “x” is a palindrome.

I then ran a double for loop multiplying each 3-digit number by every other one and testing whether the result was palindromic. If it was, the loop then tested whether the product was larger than the previous max palindrome product and updated the “max” variable accordingly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
is.pal <- function(x) {
 pal <- 0
 x <- as.character(x)
 forward <- unlist(strsplit(x, split =""))
 reverse <- rev(forward)
 if (all(forward == reverse)) {
   pal <- 1
 }
 return(pal)
}

max <- 0

for (i in 100:999) {
 for (j in 100:999) {
   if (is.pal(i*j) == 1 & i*j > max) {
     max <- i*j
   }
 }
}

max

This script actually ran very quickly to produce the correct answer. Altogether I’m quite happy with it but I’m always open to optimization suggestions.