Oxaric’s Blog

A compendium of amazing things…

Euler Project Problem #38 Solution

Posted by oxaric on November 24, 2008

It uses Ruby.


Click to directly download euler-solution-38.rb

# filename 'euler-solution-38.rb'
# By: Louis Casillas, oxaric@gmail.com

# Euler Problem #38
# What is the largest 1 to 9 pandigital that can be formed by multiplying a fixed number by 1, 2, 3, ... ?
# Example:
# 192 x 1 = 192 
# 192 x 2 = 384
# 192 x 3 = 576
# 192384576 => unique and sort => 123456789

def calculate( num )
   num_s = num.to_s
   
   if num_s.include?( "0" )
      return [false]
   end   

   if (num_s.size > num_s.split(//).uniq.join.size)
      return [false]
   end
   
   n = 2
   temp_s = ""
   temp_s += (num * 1).to_s
   temp_s += (num * 2).to_s
   
   while true
      if (temp_s.size > 9)
         return [false]
      end
      
      if (temp_s.size > temp_s.split(//).uniq.join.size)
         return [false]
      end

      if (temp_s.size == 9)

         if temp_s.include?( "0" )
            return [false]
         else
            return [true, temp_s.to_i, n]
         end
      else
         n += 1
         temp_s += (num * n).to_s
      end
   end
end

max_number = 0

for i in (1..10000)
   temp = calculate( i )

   if temp[0]
      if (max_number < temp[1])
         max_number = temp[1]
         puts "Found one: " + i.to_s + " n = " + temp[2].to_s
      end
   end   
end

puts "The max 1 to 9 pandigital number is: " + max_number.to_s

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>