algorithm - How to determine if a number is polygonal for a polygon with s sides -
a polygonal number defined being number represented dots arranged in shape of regular polygon.
for example:
triangular numbers 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, ...
square numbers 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ...
pentagonal number 0, 1, 5, 12, 22, 35, 51, 70, 92, 117, ...
and on...
there known formulas calculate of these numbers. calculate n-th s-gonal number, 1 can use formula (n^2 * (s - 2) - (n * (s - 4))) / 2
what know is, there efficient way check if given number s-gonal given s?
the obvious approach take successive values function generates s-gonal numbers until either n found, or values exceed n, has linear time complexity.
i know there formulas can used determine if number s-gonal specific values of s, 1 works s.
based on wikipedia's article on polygonal numbers can following predicate seems solve problems ran 1 op proposed:
def ispolygonal(s, x): ''' check if x s-gonal number ''' assert s > 2 , s % 1 == 0 , x % 1 == 0 # determine if x nth s-gonal number, # fail if n doesn't come out whole number n = (sqrt(8 * (s - 2) * x + (s - 4) ** 2) + (s - 4)) / (2 * (s - 2)) return n % 1 == 0
this 1 doesn't insist on int
arguments, whole numbers, i.e. 5.0 5 our purposes.
Comments
Post a Comment