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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.