-
Notifications
You must be signed in to change notification settings - Fork 0
/
figurate_numbers.py
40 lines (32 loc) · 1.13 KB
/
figurate_numbers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# for problems 044, 045, 061...
# Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers
# and are generated by the following formulae:
#
# Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ...
# Square P4,n=n^2 1, 4, 9, 16, 25, ...
# Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ...
# Hexagonal P6,n=n(2n−1) 1, 6, 15, 28, 45, ...
# Heptagonal P7,n=n(5n−3)/2 1, 7, 18, 34, 55, ...
# Octagonal P8,n=n(3n−2) 1, 8, 21, 40, 65, ...
# took the formulae above, applied the quadratic formula, and derived the tests below
from math import sqrt, modf
def is_triangular(x):
n = (sqrt(8*x + 1) - 1) / 2
return modf(n)[0] == 0.0
def is_square(x):
n = sqrt(x)
return modf(n)[0] == 0.0
def is_pentagonal(x):
n = (sqrt(24*x + 1) + 1) / 6
return modf(n)[0] == 0.0
def is_hexagonal(x):
n = (sqrt(8*x + 1) + 1) / 4
return modf(n)[0] == 0.0
def is_heptagonal(x):
n = (sqrt(40*x + 9) + 3) / 10
return modf(n)[0] == 0.0
def is_octagonal(x):
n = (sqrt(3*x + 1) + 1) / 3
return modf(n)[0] == 0.0
def triangular(n):
return int(n*(n+1)/2)