project_euler/32.rb
Code:
# Project Euler Problem 32: Pandigital Products
# https://projecteuler.net/problem=32
# 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.
def divisor_pairs(n)
(1..Math.sqrt(n)).map { |a| n % a == 0 ? [a, n / a] : nil }.compact
end
def pandigital?(a, b, c)
d = [a, b, c].map(&:to_s).join
return false unless d.size == 9
return d.chars.sort == '123456789'.chars
end
def solve()
results = []
(1_000...10_000).each do |c|
for a, b in divisor_pairs(c) do
if pandigital?(a, b, c)
puts "#{a} × #{b} = #{c}"
results << c
end
end
end
return results.uniq.sum
end
puts solve()
Output:
28 × 157 = 4396
18 × 297 = 5346
27 × 198 = 5346
12 × 483 = 5796
42 × 138 = 5796
4 × 1738 = 6952
39 × 186 = 7254
48 × 159 = 7632
4 × 1963 = 7852
45228