|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# Let d(n) be defined as the sum of proper divisors of n |
| 4 | +# (numbers less than n which divide evenly into n). |
| 5 | +# If d(a) = b and d(b) = a, where a & b, then a and b are an amicable pair. |
| 6 | +# and each of a and b are called amicable numbers. |
| 7 | +# |
| 8 | +# For example, |
| 9 | +# |
| 10 | +# The proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; |
| 11 | +# therefore d(220) = 284. |
| 12 | +# |
| 13 | +# The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. |
| 14 | +# |
| 15 | +# Evaluate the sum of all the amicable numbers under 10000. |
| 16 | + |
| 17 | +# get list of all divisors of `number` |
| 18 | +def get_divisors(number) |
| 19 | + divisors = [] |
| 20 | + (1..(Math.sqrt(number).to_i)).each do |num| |
| 21 | + if (number % num).zero? |
| 22 | + divisors << num |
| 23 | + divisors << number / num |
| 24 | + end |
| 25 | + end |
| 26 | + divisors |
| 27 | +end |
| 28 | + |
| 29 | +# get list of all proper divisors of `number` i.e. removing `number` from |
| 30 | +# the list of divisors |
| 31 | +def get_proper_divisors(number) |
| 32 | + divisors = get_divisors(number) |
| 33 | + divisors.delete(number) |
| 34 | + divisors |
| 35 | +end |
| 36 | + |
| 37 | +# implementation of a method `d` as mentioned in the question |
| 38 | +# i.e. finding sum of all proper divisors of `number` |
| 39 | +def d(number) |
| 40 | + get_proper_divisors(number).sum |
| 41 | +end |
| 42 | + |
| 43 | +# given an upper `limit`, this method finds all amicable numbers |
| 44 | +# under this `limit` |
| 45 | +def find_amicable_numbers(limit) |
| 46 | + result = [] |
| 47 | + (1...limit).each do |a| |
| 48 | + b = d(a) |
| 49 | + res = d(b) |
| 50 | + result.push(a) if (a == res) && (a != b) |
| 51 | + end |
| 52 | + result |
| 53 | +end |
| 54 | + |
| 55 | +# calling `find_amicable_numbers` method and finding sum of all such numbers |
| 56 | +# below 10000, and printing the result on the console |
| 57 | +puts find_amicable_numbers(10_000).sum |
0 commit comments