License MIT license
Lines 20
Keywords
euler (1) math (4) number (1) triangle (2)
Permissions
Owner: clawlor
Viewable by Everyone
Editable by clawlor's Friends
Hide
Easily highlight source code for your blog with our Syntax Highlighter. Join Siafoo Now or Learn More

Test if an integer is a triangle number Atom Feed 0

In Brief A triangular number is the sum of the n natural numbers from 1 to n.... more
# 's
 1def istriangle(n):
2 """
3 Tests if n is a triangle number.
4 Input:
5 n -- a positive integer
6 Output:
7 a positive integer indicating which triangle number in the series is n,
8 or False if n is not a triangle number
9 Examples:
10 >>> istriangle(1)
11 1
12 >>> istriangle(55)
13 10
14 >>> istriangle(7)
15 False
16 """
17 x = (math.sqrt(8*n + 1) - 1) / 2
18 if x - int(x) > 0: # if x is not an integer
19 return False
20 return int(x)

A triangular number is the sum of the n natural numbers from 1 to n.

Returns False if n is not a triangle number. If n is a triangle number, returns an integer indicating which triangle number in the series is n.