-
Notifications
You must be signed in to change notification settings - Fork 6
/
problem-045.rb
58 lines (45 loc) · 1.17 KB
/
problem-045.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
#!/usr/bin/env ruby
# Find the next triangle number that is also pentagonal and hexagonal.
# Check if a number is a triangle number and return the value of n
# for that number. Triangle number = n*(n+1)/2
def triangle_number?(number)
root = (-1+Math.sqrt(1+(8*number)))/2
if (root-root.to_i) == 0
return true
else
return false
end
end
# Check if a number is pentagonal
# Pentagonal number = n*(3*n-1)/2
def pentagonal_number?(number)
root = (1+Math.sqrt(1+(24*number)))/6
if (root-root.to_i) == 0
return true
else
return false
end
end
# Check if a number is hexagonal
# Hexagonal number = n*(2*n-1)
def hexagonal_number?(number)
root = (1+Math.sqrt(1+(8*number)))/4
if (root-root.to_i) == 0
return true
else
return false
end
end
###
=begin
We know that 40755 is triangle, pentagonal and hexagonal
Find the n for the hexagonal formula for 40755 and compute hexagonal numbers
for increments of n and find the next one that is also a triangle number and
pentagonal
=end
n = (1+Math.sqrt(1+(8*40755)))/4
begin
n += 1
number = n*(2*n-1)
end while(!(triangle_number?(number) && pentagonal_number?(number)))
puts "Answer: #{number.to_i}"