-
Notifications
You must be signed in to change notification settings - Fork 2
/
45.rb
63 lines (54 loc) · 1.06 KB
/
45.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Problem 45
# 06 June 2003
#
# Triangle, pentagonal, and hexagonal numbers are generated by the following
# formulae:
#
# Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
# Pentagonal Pn=n(3n-1)/2 1, 5, 12, 22, 35, ...
# Hexagonal Hn=n(2n-1) 1, 6, 15, 28, 45, ...
#
# It can be verified that T285 = P165 = H143 = 40755.
#
# Find the next triangle number that is also pentagonal and hexagonal.
class Triangle
def self.[](n)
n*(n+1)/2
end
end
class Pentagonal
def self.[](n)
n*(3*n-1)/2
end
end
class Hexagonal
def self.[](n)
n*(2*n-1)
end
end
t = 285
p = 165
h = 143
puts [ t, p, h, Triangle[t] ].inspect
loop do
h += 1
while Triangle[t] < Hexagonal[h]
t += 1
end
if Triangle[t] == Hexagonal[h]
while Pentagonal[p] < Hexagonal[h]
p += 1
end
break if Pentagonal[p] == Hexagonal[h]
end
end
puts "T(#{t})=#{Triangle[t]}"
puts "P(#{p})=#{Pentagonal[p]}"
puts "H(#{h})=#{Hexagonal[h]}"
# [285, 165, 143, 40755]
# T(55385)=1533776805
# P(31977)=1533776805
# H(27693)=1533776805
# real 0m0.639s
# user 0m0.623s
# sys 0m0.008s