丰数是其固有因数之和大于该数本身的数。欧拉工程的一个问题是:"找出所有不能写成两个富数和的正整数的和。"我应该得到:
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
这里有一些东西可以让你开始。这需要一些时间来完成。
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...]