欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

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

发布时间:2025/3/8 python 36 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 – 找到最大的公约数(赋值错误,我迫切需要你的帮助)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。