Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Pn=n(3n−1)/2

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!

like image 994
ggordon Avatar asked Dec 24 '22 05:12

ggordon


1 Answers

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()
like image 191
Eugene Yarmash Avatar answered Dec 26 '22 18:12

Eugene Yarmash