solved infinite recursion and looping using break and return statements

Question:

#a=divident b=divisor q=quotient r=remainder (a = qb + r)
def euclid(a,b):
    while True:
        q = 1       
        while max(a, b) - min(a, b) * (q + 1) > 0:
            q += 1
        else:
            r = max(a, b) - min(a, b) * q
            print('a = ', max(a, b), 'and b = ',min(a, b))
            euclid(r, min(a,b))
            
euclid(8, 3) 
print(1)

hi, i’m new to coding so it might be a dumb and obvious mistake that i unknowingly made.
I created a function to print the divident and divisor in every step of the euclidean algorithm for 8 and 3. However, i found out that the print(1) at the end doesn’t seem to execute if i place it under the euclid() function. Additional information: if i change one of the numbers to 0 into my euclid function it doesn’t work. Example: euclid(8,0)

Asked By: newtocoding

||

Answers:

Your function euclid begins with an infinite loop. However, you never stop iterating with a break or a return statement, therefore you are infinitely looping.

You are also infinitely recursing. Because euclid is calling itself and it never returns, the code never reaches your print statement.

This infinite recursion will cause a Stack Overflow Recursion error. This is because each time your function is called, the call is put on the stack. Since it never returns, the stack frame never gets destroyed.

EDIT:
The infinite recursion causes a Recursion error which is a safeguard against stack overflow by Python.

Answered By: zayaanra
def euclid(a,b):
    while True:
        q = 1       
        while max(a, b) - min(a, b) * (q + 1) > 0:
            q += 1
        else:
            r = max(a, b) - min(a, b) * q
            if r == 0:
                break
            else:
                print('a = ', max(a, b), 'and b = ',min(a, b))
                euclid(r, min(a,b))
                return False
            
euclid(273, 100) 
print(1)

Added an if statement and a break to prevent infinite recursion ,
and a return False to prevent infinite looping. Thank you so much for taking time answering my question.

Answered By: newtocoding
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.