4
\$\begingroup\$
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?

nhgrif
25.4k3 gold badges64 silver badges129 bronze badges
asked May 29, 2015 at 17:09
\$\endgroup\$
1
  • 2
    \$\begingroup\$ You are probably getting a stack overflow (the error, not the website ;)) \$\endgroup\$ Commented May 29, 2015 at 17:43

2 Answers 2

7
\$\begingroup\$

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
answered May 29, 2015 at 17:19
\$\endgroup\$
0
1
\$\begingroup\$

I would advice writing a more general function and then maybe defining an helper, like:

def polygonal(n, sides):
 return (n**2*(sides-2) - n*(sides-4)) // 2
def triangular(n):
 return polygonal(n, 3)

This may take a little bit more code, but will allow easier use of other n-gonals numbers.

Please note that you may do without triangular and call:

polygonal(n, sides=3)
answered May 29, 2015 at 17:57
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Also, note you can do triangular = functools.partial(polygonal, sides=3). \$\endgroup\$ Commented May 29, 2015 at 18:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.