Created
June 2, 2011 23:06
-
-
Save johana-star/1005539 to your computer and use it in GitHub Desktop.
Euler Project Problem #021
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Solution to Project Euler's twenty-first problem | |
# http://projecteuler.net/index.php?section=problems&id=21 | |
# Find the sum of the amicable pairs below 10000. | |
def generate_sum_of_divisors(ceiling) | |
sums = Array.new(ceiling+1, 0) | |
(0..ceiling).each do |number| | |
(1..Math.sqrt(number)).each do |num| | |
if number % num == 0 then | |
sums[number] += num | |
if number/num != num && num != 1 then | |
sums[number] += number/num | |
end | |
end | |
end | |
end | |
return sums | |
end | |
def generate_amicable_numbers(sums) | |
array = [] | |
sums.each_with_index do |sum, i| | |
if sums[sum] != nil && sum == sums[i] && i == sums[sum] && i != sum then | |
array << i | |
end | |
end | |
return array | |
end | |
a = Time.new | |
number = 10000 | |
sums = generate_sum_of_divisors(number) | |
amicable_pairs = generate_amicable_numbers(sums) | |
p amicable_pairs.inject(0) { |result, element| result + element } | |
b = Time.new - a | |
p b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment