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.
kiwi
2
[code=ruby]def t(n)
(n2+n)/2
end
def p(n)
(3*n2-n)/2
end
def h(n)
2*n**2-n
end
list = Hash.new
(284…1_000_000).map{|a| t(a)}.each{|t| list[t]=1}
(160…1_000_000).map{|b| p(b)}.each{|t| list[t].nil? ? list[t]=1 : list[t]+=1}
(140…1_000_000).map{|c| h©}.each{|t| list[t].nil? ? list[t]=1 : list[t]+=1}
puts list.delete(40755).key(3)[/code]
Moje mniej ładne rozwiązanie ale pewniejsze:
#!/usr/bin/env ruby
#n0, m0, o0 = 2, 2, 2
n0, m0, o0 = 286, 166, 144
n = n0
while true
tt, pp, hh = n*(n+1)/2, nil, nil
m = m0
while (pp = m*(3*m-1)/2) < tt
o = o0
o += 1 while (hh = o*(2*o-1)) < pp
o0 = o-1
break if pp == hh
m += 1
end
m0 = m-1
break if tt == pp && pp == hh
n += 1
end
p tt
teamon
4
[code=ruby]Triangle = Enumerator.new do |ret|
n = 1
loop do
ret << n*(n+1)/2
n += 1
end
end
T = Triangle.each
loop do
t = T.next
p t if (sq=Math.sqrt(1 + 24t)) % 1 == 0 && ((x=(1-sq)/6) > 0 && x % 1 == 0 || (x=(1+sq)/6) > 0 && x % 1 == 0) && (sq=Math.sqrt(1 + 8t)) % 1 == 0 && ((x=(1-sq)/4) > 0 && x % 1 == 0 || (x=(1+sq)/4) > 0 && x % 1 == 0)
end[/code]
[code=ruby]ta, pa, ha = [], [], []
(285…100000).each do |n|
ta << ( n * ( n + 1 ) ) / 2
pa << ( n * ( 3 * n - 1 ) ) / 2
ha << n * ( 2 * n - 1 )
end
p ha & ta & pa[/code]