読者です 読者をやめる 読者になる 読者になる

mu chance or much chance ?

日々の戯れ言

Project Euler 32

Project Euler

Problem32を解きました.

  • Pandigital products

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.

https://projecteuler.net/problem=32

問題は「『かけられる数』と『かける数』と『その積の値』をつなげた場合,1から9のパンデジタルとなるような積の総和を求めよ」.

sum = 0
ans = Array.new()

# 1桁 * 4桁 = 4桁
for i in 1..9 do
	for j in 1000..9999 do
		k = i * j
		str = (i.to_s + j.to_s + k.to_s).split("").sort.join
		if str == "123456789" && !ans.include?(k) then
			ans.push(k)
		end
	end
end

# 2桁 * 3桁 = 4桁
for i in 10..99 do
	for j in 100..999 do
		k = i * j
		str = (i.to_s + j.to_s + k.to_s).split("").sort.join
		if str == "123456789" && !ans.include?(k) then
			ans.push(k)
		end
	end
end

p ans.inject(:+)

プログラムのコメントにもありますが,
数学的な解析から,
1桁 * 4桁 = 4桁と2桁 * 3桁 = 4桁の場合だけです.