[英]findGCD function never completes
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
.我正在锻炼以改进我的编码,但是当我尝试使用此代码并运行时,终端只是冻结并且根本没有给出任何错误,在我按下
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.有很多错误,包括上面提到的不正确的
if
语句。 num/2
will calculate something but this will be a float value if num is odd; num/2
会计算一些东西,但如果 num 是奇数,这将是一个浮点值; then you do nothing with the result;那么你对结果什么都不做; same for num1/2.
与 num1/2 相同。 To find GCD you have to use integer arithmetic.
要找到 GCD,您必须使用 integer 算术。 Incidently 101 and 102 have only the GCD of 1 so maybe not the best example.
顺便说一下,101 和 102 只有 1 的 GCD,所以可能不是最好的例子。 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.
我建议你把它画成https://pythontutor.com/visualize.html#mode=edit 单步执行代码,看看它是如何工作的。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.