Luke’s Personal Website
  • Home
  • Blog
  • Projects
  • Resume

On this page

  • Project Euler Four

Project Euler Four

R
Project Euler
Author

Luke

Published

March 20, 2024

Project Euler Four

Question

A palindromic number reads the same both ways. The largest palindrome made from the product of two \(2\)-digit numbers is \(9009 = 91 \times 99\).

Find the largest palindrome made from the product of two \(3\)-digit numbers.

Let’s try using some modern packages for this, collapse is the current bleeding edge of data manipulation libraries in R, with similar speed benchmarks to polars (the fastest data manipulation package in python land).

library(magrittr)
n_digits = 3
palindrome_product_below = function(n_digits) {

    n_digit_nums = 10^(n_digits-1):10^n_digits

    numbers_one= tibble::tibble(NumsOne = n_digit_nums)
    numbers_two = tibble::tibble(NumsTwo = n_digit_nums)

    total_nums = dplyr::cross_join(numbers_one, numbers_two) |> 
        collapse::fmutate(Product = NumsOne * NumsTwo) |> 
        collapse::fmutate(StringNums = as.character(Product)) |> 
        collapse::fmutate(RevStringNums = stringi::stri_reverse(StringNums)) |> 
        collapse::fsubset(StringNums == RevStringNums) |> 
        dplyr::pull(Product) |> 
        max()

    return(total_nums)

}
print(palindrome_product_below(3))
[1] 906609

This is a simple enough operation to do, but these dplyr style verbs with speed optimization scale well to many more complex problems.