Euler Problem 4 – Largest Palindrome Product

Largest palindrome product

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.

  
check_if_palindrome = function(num) {
  if(!is.numeric(num) & (num %% 1 == 0))
    stop("Please enter only whole numbers")
  if(num > .Machine$integer.max)
     stop("Value too large")

 n = num;
 rev = 0;
 while (num > 0) {
    dig = num %% 10
    rev = rev * 10 + dig
    num = floor(num / 10)
  }
  if (n==rev)
    return(TRUE)
  else
    return(FALSE)  
}

getLargest3DigitPalindrome = function() {
  allProducts <- outer(1:999, 1:999)
  getAllPalindromes <- sapply(allProducts, check_if_palindrome)
  max(allProducts[which(getAllPalindromes==1, arr.ind = T)])
}

getLargest3DigitPalindrome()
[1] 906609

Outer function multiplies every element of x with every element of y. So allProducts have multiplication value for that respective row vs column. We apply the check_if_palindrome function to every value in allProducts. We get the max of all the values which is a palindrome.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s