-
Notifications
You must be signed in to change notification settings - Fork 0
/
project_euler_45.rb
67 lines (58 loc) · 1.09 KB
/
project_euler_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
64
65
66
67
# Triangular, pentagonal, and hexagonal
# Problem 45
# 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.
#
def t(n)
n * (n + 1) / 2
end
def p(n)
n * (3 * n - 1) / 2
end
def h(n)
n * (2 * n - 1)
end
i = 285
p_offset = 0
h_offset = 0
p_found = false
h_found = false
loop do
i += 1
triangle = t(i)
loop do
pentagonal = p(p_offset)
if pentagonal > triangle
break
elsif pentagonal == triangle
p_found = true
break
else
p_offset += 1
end
end
loop do
hexgonal = h(h_offset)
if hexgonal > triangle
break
elsif hexgonal == triangle
h_found = true
break
else
h_offset += 1
end
end
if p_found && h_found
puts triangle
break
else
p_found = false
h_found = false
end
end