Project Euler : Problem 38 in Ruby

40 problems down, 10 more till level 2!

The real trick here is to cut down on the numbers you check. Since the problem gives you 918273645 as an example we know the answer must be greater than or equal to it…meaning we only need to check digits that start with 9!

I don’t actually do it because I couldn’t figure out an elegant way to do, but it runs in just a few milliseconds so it’s fast enough in my book.

Another important factor to note is that you only need to check numbers up to 9_876 since this is the first ‘half’ of the largest pandigital possible.

Those two tricks will cut down the calculations you need to run to just a few thousand.

Problem 38

What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, … , n) where n 1?

def get_pandigital? n
  nums = []
  (1..9).each do |digit|
    nums += (n * digit).to_s.split ''
    return 0 if nums.size != nums.uniq.size || nums.include?('0')
    return nums.join('').to_i if nums.size == 9

solution = 0

(9..9_876).each do |n|
  # could do better by only looking at 9's!
  result = get_pandigital? n
  if result > solution
    solution = result

puts solution

Check out all of my solutions on bitbucket!