[英]Recursive Euclidean GCD algorithm with function
我在問我必須顯示的遞歸部分(在 function 中,還有另一個參數verbose: bool
)。 我需要計算兩個數字的 gcd。 但是如何顯示商和 rest 和操作?
像這樣:
By setting q the quotient of the integer division of a by b, let us calculate for example
the gcd of 90 and of 35 (gcd (90,35), so a = 90 and b = 35):
a = b × q + r
As for 90/35 we have q = 2 and r = 20, then 90 = 35 × 2 + 20
According to Euclid, pgcd (90.35) = pgcd (35.20). So we start over with the new values:
35 = 20 × 1 + 15
According to Euclid, pgcd (35.20) = pgcd (20.15). So we start over with the new values:
20 = 15 × 1 + 5
According to Euclid, pgcd (20.15) = pgcd (15.5). So we start over with the new values:
15 = 5 × 3 + 0
15 is divisible by 5 so we stop and pgcd (15.5) = pgcd (20.15) = pgcd (35.20) =
pgcd (90.35) = 5
Write the code of the euclid function (a: int, b: int, verbose: bool = False) -> int which
calculates the gcd of a and b and, if the verbose parameter is True, displays the
different steps of the algorithm of the calculation (the values of a, b, q and r).
我試過這個,但這是完整的,我對此一無所知。 我什至不知道什么是什么順序。
我試過的:
def gcd(a,b, verbose = False):
r = a%b
q:int
if r == 0:
q = a//b
print(b)
return b
else:
verbose = True
while r != 0:
result = b*q+r
a= result
b = result
r = b
return result
num1 = int(input('chose a number'))
num2 = int(input('chose a second number'))
print(gcd(num1,num2, verbose = False))
這是 output:
“分配前”是的,但根據問題,我不知道把q
放在哪里,除了if r== 0
then q = a//b
。
And I don't know how to make the recursive part how I'm supposed to loop on a = b*q + r
and say that if r
is not 0
then a
is b
and b
is r
and to do it until r
is 0
並打印 gcd,如果verbose
為True
我必須描述每個計算並打印a
、 b
、 r
和q
。
您可以通過以下方式使用遞歸方法執行此操作:
def gcd(a,b,verbose=False):
if b>a:
return gcd(b,a,verbose)
r=a%b
if r==0:
if verbose==True:
q=a//b
print("a=",a,"b=",b,"q=",q,"r=",r)
return b
else:
if verbose==True:
q=a//b
print("a=",a,"b=",b,"q=",q,"r=",r)
return gcd(b,r,verbose)
您的分配並沒有說您必須使用遞歸,事實上,如果您不使用並使用迭代(即循環)來代替它會更簡單。
這就是我的意思:
def gcd(a: int, b: int, verbose: bool = False) -> int:
while b != 0:
if verbose:
print(f'{a=}, {b=}')
q = a // b
r = a % b
a = b
b = r
return a
#num1 = int(input('chose a number'))
#num2 = int(input('chose a second number'))
num1, num2 = 90, 35 # Hardcode for testing.
Output:
a=90, b=35
a=35, b=20
a=20, b=15
a=15, b=5
gcd(num1, num2, verbose=True)=5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.