abundant number是一个数字,其正确除数之和大于数字本身。一个Project Euler question说:“求出所有正整数的总和,这些正整数不能写成两个数字的总和。”我应该得到:
12, 18, 20, 24, etc.
代码是:
def check_abundant(x)
total(x) > x
end
def total (x)
sum = 1
(2..Math.sqrt(x)).each do |i|
sum = sum + x + x/i if x%i == 0 && i != Math.sqrt(x)
end
sum
end
def non_abundant_sums
abundant_arr = []
s = 0
(12..28123).each do |x|
if check_abundant(x)
abundant_arr << x
end
(1..28123).each do |x|
s = s + x unless abundant_arr.include? (total(x) - x)
end
s
end
puts non_abundant_sums
当我打印abundant_arr
时,我得到了
12, 14, 15
答案 0 :(得分:0)
这是让你入门的东西。完成需要一段时间。
def proper_divisors(num)
(1...num).select { |n| num % n == 0 }
end
def abundant?(n)
proper_divisors(n).reduce(:+) > n
end
arr = (12..28123).map { |n| print "." if n % 100 == 0; n if abundant?(n) }.compact
=> [12, 18, 20, 24, 30, 36, 40...]