The Python Oracle

Python - is pentagonal number check

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Breezy Bay

--

Chapters
00:00 Python - Is Pentagonal Number Check
00:43 Accepted Answer Score 8
01:09 Answer 2 Score 2
01:53 Answer 3 Score 1
02:11 Answer 4 Score 0
02:34 Thank you

--

Full question
https://stackoverflow.com/questions/3739...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #math #sequence

#avk47



ACCEPTED ANSWER

Score 8


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



ANSWER 2

Score 2


The reason why your code doesn't work, is you're reducing the range of integers tested too much. It is interesting to reduce it (using sqrt) but it causes you to miss some values.

Instead, you can increase the tested range:

#!/usr/bin/env python3

from math import sqrt

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

for i in range(500):
    if is_pent(i):
        print(str(i) + " is pentagonal")

Test output:

$ ./test_script3.py
0 is pentagonal
1 is pentagonal
5 is pentagonal
12 is pentagonal
22 is pentagonal
35 is pentagonal
51 is pentagonal
70 is pentagonal
92 is pentagonal
117 is pentagonal
145 is pentagonal
176 is pentagonal
210 is pentagonal
247 is pentagonal
287 is pentagonal
330 is pentagonal
376 is pentagonal
425 is pentagonal
477 is pentagonal

EDIT: of course, you'd better use a shorter code, like suggested in eugene y answer




ANSWER 3

Score 1


you can use fsolve to get athe root of the equation generated dynamically using your number. for Example

import numpy
from scipy.optimize import fsolve

def root(x,n):
    return ((3*x*x-x)/2)-n

n = 70 #number to check if pentagonal or not

function_root = fsolve(root,n/2,n)

if function_root == int(function_root):
    print "number is pentagonal number"



ANSWER 4

Score 0


Here is a version that doesn't use pesky floats:

def sqrt(n):
    "Integer square root"
    assert isinstance(n, int)
    x = n
    y = (x + 1) // 2
    while y < x:
        x = y
        y = (x + n // x) // 2
    return x

def is_pentagonal(n: int):
    """Check if a number is pentagonal.
    Ref: https://en.wikipedia.org/wiki/Pentagonal_number"""

    k = 24 * n + 1
    sqrt_k = sqrt(k)

    if sqrt_k * sqrt_k == k and (sqrt_k + 1) % 6 == 0:
        return True
    else:
        return False

for i in range(100):
    if is_pentagonal(i):
        print(i)

Output:

1
5
12
22
35
51
70
92