You're getting an exception because 30,000 stack frames is a rather large number :-)
You solve it by using recursion in a more circumspect manner. The ideal problems to be solved recursively are those which reduce the "search space" quickly (a).
For example, binary tree traversal where your search space is halved each time you recur:
def find (searchkey, node):
if node = NULL:
return NULL
if searchkey = node.key:
return node
if searchkey < node.key:
return find (searchkey, node.left)
return find (searchkey, node.right)
Adding two unsigned integers (and your own algorithm above) are not a good fit for recursion because you'll blow out your stack allocation long before the results are calculated.:
def add (a, b):
if a = 0:
return b
return add (a-1, b+1)
(a) Search space can be defined as your entire set of possible answers. You want to reduce it as quickly as possible.
And , as an aside, the ideal problems for recursion have nothing to do with stack space in a theoretical/mathematical sense, they're just any problem that can be expressed as:
- the same or similar problem with a "simpler" argument.
- a terminating condition with the "simplest" argument.
("simple" , in this sense, means approaching the terminating condition).
Theoretical/mathemeatical approaches wouldn't need to take stack space into account but we, as computer scientists, must. Reality sets limits :-)
See also When would I not use recursion? and Situations where you would convert recursion to iteration.