Skip to content

Commit 20d437b

Browse files
committed
did 38
1 parent 025ab11 commit 20d437b

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Integer right triangles
2+
# Problem 39
3+
# If p is the perimeter of a right angle triangle with integral
4+
# length sides, {a,b,c}, there are exactly three solutions for p = 120.
5+
6+
# {20,48,52}, {24,45,51}, {30,40,50}
7+
8+
# For which value of p ≤ 1000, is the number of solutions maximised?
9+
10+
# Solution by Sam Gerber
11+
12+
13+
14+
15+
# This method returns an array of pythagorean triples whose sum does not
16+
# exceed max_perimeter
17+
18+
19+
def pythagorean_triples(max_perimeter)
20+
triples = {}
21+
# a = b = c = 0
22+
23+
(1...max_perimeter).each do |a|
24+
(a + 1 ...max_perimeter).each do |b|
25+
c = Math.sqrt(a**2 + b**2)
26+
if c % 1 == 0
27+
c = c.to_i
28+
perimeter = a + b + c
29+
if triples[perimeter] == nil && perimeter < max_perimeter
30+
triples[perimeter] = [[a, b, c]]
31+
elsif perimeter < max_perimeter
32+
triples[perimeter] << [a, b, c]
33+
end
34+
end
35+
end
36+
end
37+
triples
38+
end
39+
40+
hash = pythagorean_triples(1_000)
41+
best = [0, 0]
42+
hash.each do |perimeter, triples|
43+
if triples.count > best[1]
44+
best = [perimeter, triples.count]
45+
end
46+
end
47+
puts best
48+
puts ""
49+
print hash[best[0]]

0 commit comments

Comments
 (0)