HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Finding the nth triangular number

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nthnumberthefindingtriangular

Problem

def triangularNumber(n):
    if(n == 1):
        return 1
    else:
        return triangularNumbers(n-1)+n


works great to find the nth triangular number up to 996...
I get some error in the recursion after 996. But can tell what it is because it just keeps running through the loop. Anyone see the error?

Solution

Using recursion is generally advised against, as it takes longer that iterating, and can run into what you ran into, a RuntimeError: maximum recursion depth exceeded. Note you can change the maximum recursion depth, but it is generally advised against, and can lead to stack or memory overflows. In this case, you should iterate.

def triangular_number(n):
    i = n
    while True:
        if i == 1:
            return n
        i -= 1
        n += i


(This keeps running in the same function call, reducing the addition factor by one each time.)

Or better yet, use a range (or xrange for Python 2):

def triangular_number(n):
    for i in range(n):  # range(3) is a generator for [0, 1, 2]
        n += i
    return n


Or better yet, use sum:

def triangular_number(n):
    return sum(range(n + 1))


Or, even better, use the formula for triangle numbers.

def triangular_number(n):
    return n * (n + 1) // 2  # Convert to int for Python 2

Code Snippets

def triangular_number(n):
    i = n
    while True:
        if i == 1:
            return n
        i -= 1
        n += i
def triangular_number(n):
    for i in range(n):  # range(3) is a generator for [0, 1, 2]
        n += i
    return n
def triangular_number(n):
    return sum(range(n + 1))
def triangular_number(n):
    return n * (n + 1) // 2  # Convert to int for Python 2

Context

StackExchange Code Review Q#92175, answer score: 6

Revisions (0)

No revisions yet.