findGCD function never completes

Question:

I was exercising to improve my coding but when I try to use this code and run, terminal just freezes and not giving any error at all, I cant do anything either until I press ctrl+c. Cause of its not giving error I don’t know what did I wrong.

# 31. Write a Python program to compute the greatest common divisor (GCD) of two positive integers.

def findGCD(num,num1):
    numDivided = 0
    num1Divided = 0
    while True:
        num/2
        numDivided+=1
        num1/2
        num1Divided+=1
        if num and num1 == 1 or 0:
            break
    gcd = numDivided*num1Divided
    print(gcd)

findGCD(101,102)
Asked By: Taha

||

Answers:

There are numerous mistakes including the incorrect if statement referred to above. num/2 will calculate something but this will be a float value if num is odd; then you do nothing with the result; same for num1/2. To find GCD you have to use integer arithmetic. Incidently 101 and 102 have only the GCD of 1 so maybe not the best example. The code below works. I suggest you paint it into https://pythontutor.com/visualize.html#mode=edit to step through the code and see how it works.

def findGCD(num, num1):
    if num > num1:
        hold = num1
    else:
        hold = num
    for i in range(1, hold + 1):
        if ((num % i == 0) and (num1 % i ==0)):
            gcd = i
    return gcd
Answered By: user19077881
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.