euler/euler009.rb

31 lines
753 B
Ruby
Raw Normal View History

2014-04-25 23:59:14 +00:00
def generate_pythagorean_triples(upper_bound)
list_of_triples = []
a = 2
b = 3
while a < upper_bound
b = a + 1
while b < upper_bound
c = Math.sqrt(a**2 + b**2)
list_of_triples << [a, b, c.to_i] if c % 1 == 0 #this is a check that the sqrt is an integer
b += 1
end
a += 1
end
list_of_triples
end
def sums_of_triples(list_of_triples)
hash_of_sums = {}
list_of_triples.each do |triple|
hash_of_sums[triple] = triple.inject(:+)
end
hash_of_sums
end
def find_pythagorean_sum(upper_bound, sum_to_match)
hash_of_sums = sums_of_triples(generate_pythagorean_triples(upper_bound))
hash_of_sums.detect { |key, value| value == sum_to_match }
end
puts find_pythagorean_sum(500, 1000).first.inject(:*)