日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python最大约数是_python – 找到最大的公约数(赋值错误,我迫切需要你的帮助)

發布時間:2025/3/8 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python最大约数是_python – 找到最大的公约数(赋值错误,我迫切需要你的帮助) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我有一個作業(作業)如下:

Write a program which enters two positive integers a and b from the

keyboard. Also write a recursive function for determining the gcd

(greatest common divisor) of a and b using Euclid’s algorithm.

According to this algorithm if the first number is divisible by the

second one then thesecond one is the gcd. If this is not the case then

the gcd of the second number and the remainder of a=b has to be

determined. The result should be printed on the screen outside of the

function.

這是我的解決方案:

a=int(input("Enter the first number: "))

b=int(input("Enter the second number: "))

def GCDfinder(m,n):

z=abs(m-n)

if (m-n)==0:

return n

else:

return GCDfinder(z,min(m,n))

print (GCDfinder(a,b))

這個答案得到了50%.我認為分級的老師的助手不知道她做了什么.她的評論如下:

That is not the method described in the assignment. You should first

check if a%b==0 then return b. Or return gcd(b, a%b) Also check that

the input is positive and a>b

2-)絕對不需要檢查> b并且也不需要檢查輸入是否為正,因為我使用了abs()

TA沒有誤導作業嗎?還是我錯了?

最佳答案 雖然你實現的確實是一個GCD查找器,但它不是Euclid的算法

這就是你所做的:

if the two numbers are equal

return either one as the GCD

else

return the GCD of the absolute difference between them and the smaller number

您的算法通過重復減法找到GCD.雖然這沒有錯,但肯定不是Euler的算法(雖然它很接近).

歐拉的算法確實:

if the smaller number perfectly divides the larger

return the smaller number as the GCD

else

return the GCD of

1. the remainder from dividing the bigger number by the smaller

2. the smaller number

因為Euclid的算法使用模數運算符,所以它會經歷更少的步驟,而實際上計算的算法與算法相同.結果,它更有效率.

這是Euclid算法的一個實現:

def GCDfinder(a,b):

while b != 0:

a,b = b, a%b

return a

>>> GCDfinder(12,20)

4

>>> GCDfinder(17,20)

1

>>> GCDfinder(3,4)

1

總結

以上是生活随笔為你收集整理的python最大约数是_python – 找到最大的公约数(赋值错误,我迫切需要你的帮助)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。