0

I'm trying to solve this excercise:

https://projecteuler.net/problem=12

Unfortunately, I receive the error message:

RuntimeError: maximum recursion depth exceeded while calling a Python object

The programm first calls the divisor-function, then calculates the triangle number for n, then checks whether the number is prime or not, and if it is, it directly checks the triangle number for n+1 because there is no prime number with 500 divisors by definition. If it isn't a prime nunmber, it is supposed to check the divisors of the triangle number as long as I haven't found 500 of them.

def triangle_number(n):
    tri_number = int(n*(n+1)/2)  # calculate triangle number for n
    return tri_number


def divisors(n):
    tri_number = triangle_number(n)
    if isprime(tri_number) is not True:  # check if triangle number is prime
        counter = 0
        while counter < 500:  # as long as we don't have enough divisors
            for x in range(1, tri_number+1):
                if tri_number % x == 0:     # check every triangle number for
                                            # their divisors
                    counter = counter + 1
                divisors(n+1)  # if for-loop breaks, check the next tri number
    else:
        divisors(n+1)  # do the same if the number is already prime


def isprime(n):
    [...]


def main():
    print(divisors(1))


if __name__ == '__main__':
    main()
abcd
  • 10,215
  • 15
  • 51
  • 85
Julian
  • 311
  • 1
  • 3
  • 12
  • 3
    Possible duplicate of [Python recursive function error: "maximum recursion depth exceeded"](https://stackoverflow.com/questions/2401447/python-recursive-function-error-maximum-recursion-depth-exceeded) – MLavrentyev Oct 05 '17 at 15:13
  • 1
    Recursive calls aren't free, and each layer of recursion takes up space in memory. If you're running up against the recursive depth limit, that's a pretty clear sign that you're trying to recursively solve a problem that doesn't need to be approached in that manner. Try an iterative solution. – Patrick Haugh Oct 05 '17 at 15:14
  • Won't solve issue, but `if not isprime(tri_number):` or `if isprime(tri_number) is not True:` rather than the comparison to `True` – toonarmycaptain Oct 05 '17 at 15:28

1 Answers1

3

Python is not a functional programming language (although it has some functional parts in it).

Therefore, recursion has not a complete funcionality inside Python, there is a recursion depth limit. That's the error you're facing. You hit the recursion depth limit.

Try to implement this using function calls and loops instead of using recursion.

See Python Recursion Limit

janscas
  • 619
  • 4
  • 13