ggordon ggordon - 5 months ago 23
Python Question

Python - is pentagonal number check

I am trying to write a check to determine whether a number is pentagonal or not. The pentagonal numbers are numbers generated by the formula:


i.e. the first pentagonal numbers are:

1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...

My code throws up False when the answer should be True so it's clearly incorrect, but I'm struggling to see why. It is as follows:

from math import sqrt
def is_pent(n):
ans = any((x*((3*x)-1))/2 == n for x in range(int(sqrt(n))))
return ans

I would be thankful for some help!


According to Wikipedia, to test whether a positive integer x is a pentagonal number you can check that ((sqrt(24*x) + 1) + 1)//6 is a natural number. Something like this should work for integers that aren't very big:

from math import sqrt 

def is_pentagonal(n):
    k = (sqrt(24*n+1)+1)/6
    return k.is_integer()