Project Euler Problem 45

Triangle, pentagonal, and hexagonal numbersを同時に満たす数をもとめる。

Triangleとhexagonalの関係は一個おきだとすぐにわかるので、数字を比較して小さいほうの数をnextさせるようにしてみた。

def tri():
    i = 1
    while(1):
        yield i*(i+1)/2
        i += 2

def penta():
    j = 1
    while(1):
        yield j*(3*j-1)/2
        j += 1

t = tri()
p = penta()

thn = t.next()
pn  = p.next()

while(1):
    if thn > pn:
        pn  = p.next()
    elif pn > thn:
        thn = t.next()
    else:
        print thn
        pn  = p.next()
        thn = t.next()

Comments