Test if an integer is a triangle number
0
Updated over 10 years ago (31 Jul 2008 at 10:55 AM)
recent activity
In Brief | A triangular number is the sum of the n natural numbers from 1 to n.... more |
Language | Python |
# '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.
Add a Comment