【发布时间】:2016-07-02 23:27:32
【问题描述】:
为什么include 方法不能正常工作?最初的问题来自Euler project,问题23。我不知道如何调试它。
我的代码:
def proper_divisors(n)
(1...n).select {|x| n % x == 0 }.inject(0){|x,y| x + y}
end
def abundant?(n)
(1...n).select {|x| n % x == 0 }.inject(0){|x,y| x + y} > n
end
def non_abundant_sums
s = 0
arr = (12..40).select { |n| n if abundant?(n) }
p arr
(1..40).each do |x|
p x unless arr.include?(proper_divisors(x) - x)
s = s + x unless arr.include?(proper_divisors(x) - x)
end
s
end
p non_abundant_sums
在上述代码中使用 p x unless arr.include?(proper_divisors(x) - x) 会打印 1 到 40:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40
我希望它打印的是 1 到 39:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 31, 33, 34, 35, 37, 39
【问题讨论】:
-
您的
arr等于[12, 18, 20, 24, 30, 36, 40]。是不是应该这样? -
@Aleksey 是的!
-
为什么
abundant不使用proper_divisors?这些方法几乎相同。 -
@Aleksey 我不知道如何让它变得简单。你能帮我解决这个问题吗?
-
坦率地说,我从数学的角度看不懂问题。您的
proper_divisors(x)- x中没有一个包含在 arr 中。从数学的角度来看是不是错了?