Python Forum
Recursive Solution - Greatest Common Denominator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursive Solution - Greatest Common Denominator
#1
Hello. I am trying to understand Recursives. Below is a code given us while taking a course. Can anyone explain to me (map out) what is going on inside this code step by step? the code gives the greatest common denominator. The answer is 4. I have been trying to work this out on my white board for the past several hours. I am just unclear as to what is going on inside to get this answer. Pete




def gcdRecur(a,b): 											
    if b == 0:
        return a
    return gcdRecur(b, a%b)
print(gcdRecur(8,12))
Reply
#2
gcdRecur receives two arguments, so would be called like gdcRecur(value1, value2).
obviously if value2 (b) is 0 a is the answer, and is returned, otherwise the function
keeps calling itself this time with value1 being the old value2 and value 2 being the division remainder of value1/value2
the best way to see this, is to add some print statements (and an iteration counter)
so modify the code a bit (to include iteration count):
def gcdRecur(count, a,b):
    print('iteration: {}, a: {}, b: {}'.format(count, a, b))
    if b == 0:
        return a
    return gcdRecur(count + 1, b, a%b)

print('results: {}'.format(gcdRecur(1, 8, 12)))
results:
Output:
iteration: 1, a: 8, b: 12 iteration: 2, a: 12, b: 8 iteration: 3, a: 8, b: 4 iteration: 4, a: 4, b: 0 results: 4
Reply
#3
Thank you Larz60+
I will probably look at this all day to understand and comprehend. I will also incorporate an iteration counter into those coding problems I don't understand. I can't wait to start testing this to get a better understanding of the internal workings of this code. Thanks again for the help. Pete
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,377 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Multiplication Recursive Solution - What's Going On Inside the Code? emerger 1 2,626 Mar-04-2018, 07:11 AM
Last Post: ka06059
  common elements of a list Skaperen 5 9,417 Mar-22-2017, 10:13 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020