簡體   English   中英

findGCD function 永遠不會完成

[英]findGCD function never completes

我正在鍛煉以改進我的編碼,但是當我嘗試使用此代碼並運行時,終端只是凍結並且根本沒有給出任何錯誤,在我按下ctrl+c之前我無法做任何事情。 它沒有給出錯誤的原因我不知道我做錯了什么。

# 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)

有很多錯誤,包括上面提到的不正確的if語句。 num/2會計算一些東西,但如果 num 是奇數,這將是一個浮點值; 那么你對結果什么都不做; 與 num1/2 相同。 要找到 GCD,您必須使用 integer 算術。 順便說一下,101 和 102 只有 1 的 GCD,所以可能不是最好的例子。 下面的代碼有效。 我建議你把它畫成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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM