ggordon - 10 months ago 83

Python Question

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

`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!

Answer

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()
```