簡體   English   中英

在遞歸函數中使用歐幾里得算法的問題

[英]Problem using Euclid's algorithm in recursive function

我是初學者,現在已經在 PythonTutor 上閱讀這段代碼一段時間了,我在 27 個步驟中獲得了“final”的正確值,但似乎無法弄清楚如何讓 while 循環停止執行和計算余數。 如何從 if 循環中獲取返回值以成為程序的最終輸出? 在這種情況下,我們使用 Euclid 算法進行計算。

def gcdRecur(a, b):
    '''
    a, b: positive integers
    
    returns: a positive integer, the greatest common divisor of a & b.
    '''
final=''    
high=max(a,b)
    result=min(a,b)
    while high%result>0:
        result-=1
        return result*gcdRecur(b,(a%b))
    if high%result==0:
        final=result
        return final
a=1071 
b=462
final_ans=gcdRecur(a,b)
print(final_ans)
        

我認為你的電線越過了歐幾里得。 如果你堅持輸入是正整數(即不是 0 也不是負數),那么你可以使用 Euclid 的基於減法的算法:

def gcdRecur(a, b):
    '''
    a, b: positive integers
    returns: a positive integer, the greatest common divisor of a & b.
    '''

    if a == b:
        return a

    if a > b:
        a -= b
    else:
        b -= a

    return gcdRecur(a, b)

並避免min()max()和模數 ( % )。 如果您使用 Euclid 算法的模數變體,那么您不需要對輸入值進行如此嚴格的約束,並且可以簡單地遞歸表示:

def gcdRecur(a, b):
    return a if not b else gcdRecur(b, a % b)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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