python – 找到最大的公约数(赋值错误,我迫切需要你的帮助)
我有一个作业(作业)如下:
这是我的解决方案: 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%.我认为分级的老师的助手不知道她做了什么.她的评论如下:
1-)我使用的方法是基于欧几里德定理. 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 – sklearn.metrics.mean_squared_error越大越好(否
- python – 如何在Pandas中将negative列和Nan列值更改为Zero
- Python新手写爬虫全过程记录分析
- python – 参数必须是9项序列,而不是datetime.datetime
- 零基础写python爬虫之抓取糗事百科代码分享
- python – `in`对`__contains__`有多少优化?
- 在Python中对字符串前缀执行二进制搜索
- python-2.7 – 如何在Tensorflow中使用CheckpointReader恢复
- python – 理解列表理解
- 听说各大网站的色情图片识别都是用的这个程序?Python识别色