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

mu chance or much chance ?

日々の戯れ言

Project Euler 23

Project Euler

Problem23を解きました.

  • Non-abundant sums

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

https://projecteuler.net/problem=23

問題は「2つの過剰数の和で表現できない自然数の総和を求めよ」.

def getSumDivisor(num)
	sum = 0
	i = 1
	while i * i < num do
		if num % i == 0 then
			sum += i
			sum += (num / i)
		end
		i = i + 1
	end
	
	if i * i == num then
		sum += i
	end
	return sum
end

def isAbundantNumber(num)
	return (getSumDivisor(num) - num) > num
end

sum = 0
data = Array.new()
check = Array.new()
list = Array.new()
for i in 1..28123 do
	check.push(i)
	if isAbundantNumber(i) then
		data.push(i)
	end
end

for i in 0..data.length - 1 do
	for j in 0..data.length - 1 do
		list.push(data[i] + data[j])
	end
end

p (check - list).inject(:+)

ヒントから,28123より大きい任意の自然数は2つの過剰数の和で書けるため,
28123以下の自然数から過剰数をリストします.
そして,そのリストから,2つの過剰数の和で表現できる自然数をリストし,
1から28123の集合からそのリストの差集合を求めることで,
2つの過剰数の和で表現できない自然数のリストを求めています.