Project Euler #45: Triangular, pentagonal, and hexagonal

  • + 0 comments

    Simple and understandable solution in Python :

    def is_triangular(x):
        return True if (1+8*x)**0.5==int((1+8*x)**0.5) else False
    def is_pentagonal(x):
        return True if (1+24*x)**0.5==int((1+24*x)**0.5) and int((1+24*x)**0.5+1)%6==0 else False
        
    n,a,b=map(int,input().strip().split())
    np=int((1+24*n)**0.5+1)//6
    nh=int((1+8*n)**0.5+1)//4
    if a==3:
        for i in range(1,np):
            p=i*(3*i-1)//2
            if is_triangular(p):
                print(p)
    else:
        for i in range(1,nh):
            h=i*(2*i-1)
            if is_pentagonal(h):
                print(h)