Project Eueler: problem21
問題
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
回答
def calc_dev(n) y = [1] i = 2 while i <= n/2 y << i if n % i == 0 i += 1 end return y end def chk_ami(n) sum1 = calc_dev(n).inject(0){|sum,x| sum + x} sum2 = calc_dev(sum1).inject(0){|sum,x| sum + x} if n == sum2 && n != sum1 return true else return false end end def find_total_ami(n) total = 0 1.upto(n).each do |v| total += v if chk_ami(v) end return total end p find_total_ami(10000)
備考
遅い。
Finished in 45.48 seconds