Julian
Julian

Reputation: 309

What is the value of the first triangle number to have over five hundred divisors?

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()

Upvotes: 0

Views: 273

Answers (1)

janscas
janscas

Reputation: 629

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

Upvotes: 3

Related Questions