project_euler/9.rb
Code:
# Project Euler Problem 9: Special Pythagorean Triplet
# https://projecteuler.net/problem=9
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a² + b² = c².
# For example, 3² + 4² = 9 + 16 = 25 = 5².
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def solve(n)
sqr_n = Hash[(0..n / 2).zip (0..n / 2).to_a.map { |n| n * n }].invert
(1..n / 2).to_a.combination(2).to_a.each do |a, b|
c = sqr_n[a * a + b * b]
next if c == nil
return a * b * c if a + b + c == n
end
return -1
end
puts solve(12)
puts solve(1000)
Output:
60
31875000