Solutions to Project Euler 32: Products whose multiplicand/multiplier/product identity is one through nine pandigital

Project Euler 32: Pandigital Products

Peter Prevos

Peter Prevos |

388 words | 2 minutes

Share this content

Project Euler 32 returns to pandigital numbers, which are numbers that contain one of each digit. Like so many of the Euler Problems, these numbers serve no practical purpose whatsoever. Just like palindromic products, other than some entertainment value and increasing your understanding of numbers.

You can find all pandigital numbers with digits zero to nine in sequence A050278 of the Online Encyclopedia of Integers. The Numberphile video below explains everything you ever wanted to know about pandigital numbers but were afraid to ask.

Why 381,654,729 is awesome – Numberphile.

Project Euler 32 Definition

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

HINT: Some products can be obtained in more than one way, so be sure to only include it once in your sum.

Proposed Solution

The pandigital.9() function tests whether a string classifies as a pandigital number. The pandigital.prod vector stores the multiplication.

The only way to solve this problem is by brute force and try all multiplications. We can limit the solution space to a manageable number. The multiplication result needs to have ten digits. For example, when the starting number has two digits, the second number should have three digits so that the total has four digits, e.g., 39 × 186 = 7254. When the first number only has one digit, the second number needs to have four digits.

  ## Project Euler 32: Pandigital Products

  pandigital.9 <- function(x) # Test if string is 9-pandigital
      (length(x)==9 & sum(duplicated(x))==0 & sum(x==0)==0)

  ## Brute force
  pandigital.prod <- vector()
  i <- 1
  for (m in 2:100) {
    if (m < 10) 
      n_start <- 1234 
    else 
      n_start <- 123
    for (n in n_start:round(10000 / m)) {
                                          # List of digits
      digs <- as.numeric(unlist(strsplit(paste0(m, n, m * n), "")))
                                          # is Pandigital?
      if (pandigital.9(digs)) {
        pandigital.prod[i] <- m * n
        i <- i + 1
        print(paste(m, "*", n, "=", m * n))
      }
    }
  }
  answer <- sum(unique(pandigital.prod))
  print(answer)

Share this content

You might also enjoy reading these articles

Project Euler 35: Circular Primes below One Million

Project Euler 144: Laser Beams and Elliptical Billiards

Project Euler 33: Digit Cancelling Fractions