Last active
August 29, 2015 14:27
-
-
Save ochaochaocha3/4f2d7d5b2d6c3fe1a9ee to your computer and use it in GitHub Desktop.
2015-08-19 Code Kata2 問題 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 問題 6. A は 0 でない整数とし、<A> は A の約数の和を表すものとします。 | |
# たとえば、<8> = 1 + 2 + 4 + 8 = 15 です。 | |
# 約数のリストを求める | |
def divisors(n) | |
# 1、n は必ず含まれる | |
# n/2 < d < n である d で n を割ると必ず 1 より大きく 2 未満になる | |
# ので、d は約数ではない | |
[1] + (2..(n / 2)).select { |d| n % d == 0 } + [n] | |
end | |
# 約数の和を求める | |
def sum_of_divisors(n) | |
divisors(n).reduce(0, &:+) | |
end | |
# 6.1 解答 | |
answer1 = sum_of_divisors(16) - sum_of_divisors(25) | |
# 6.2 解答 | |
answer2 = (12..24).select { |n| sum_of_divisors(n) == 24 } | |
# 出力 | |
puts("6.1 <16> - <25> = #{answer1}") | |
puts("6.2 <A> = 24 となる A は #{answer2}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment