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

mu chance or much chance ?

日々の戯れ言

Project Euler 34

Project Euler

Problem34を解きました.

  • Digit factorials

145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.

Find the sum of all numbers which are equal to the sum of the factorial of their digits.

Note: as 1! = 1 and 2! = 2 are not sums they are not included.

https://projecteuler.net/problem=34

問題は「ある整数の各桁の数の階乗の総和がその整数と一致するような整数の総和を求めよ.ただし,1! = 1 と 2! = 2 は総和に含めない」.

$memo = {}

def fact(num)
	if num == 0 || num == 1 then
		return 1
	end
	mul = 1
	for i in 2..num do
		mul *= i
	end
	return mul
end

for i in 0..9 do
	$memo[i] = fact(i)
end

def func(num)
	sum = 0
	while num > 0 do
		sum += $memo[num % 10]
		num /= 10
	end
	return sum
end

sum = 0
for i in 3..9999999 do
	if i == func(i) then
		sum += i
	end
end

p sum

数学的な解析から,繰り返し数を決めています.