gpt4 book ai didi

python - 找出最大公约数

转载 作者:太空宇宙 更新时间:2023-11-04 07:22:35 24 4
gpt4 key购买 nike

def gei(a, b):
'''
a, b: only positive integers! If you don't, we will make you. Max 1337
For extracting the juice of the numbers in the form of a common divider
'''
#Not Ruby, no to_i, but int()
smallest = int(abs(min(a, b)))
biggest = int(abs(max(a, b)))
print "You inputed: ", smallest, " and ", biggest, " their order doesn't matter."
print "Do you want to see guess numbers? Type 'yes', if you do! "
selection = raw_input()
print
print
#To evade infinite loops and too big numbers, we use count.
count = 0
ans = smallest
truth = str(selection) == str('yes')
def condition(ans, base):
ans1 = base % ans == 0
return ans1
while condition(ans, biggest) == False or condition(ans, smallest) == False:
ans -= 1
count += 1
if count >= 1337:
break
elif truth == True:
print ans
if truth == True:
print
print
print "After weeks of calculation, here is your greater common divider: "
return ans

是的,8 年级的信息学作业是提取常见的更大的分隔符。我在想,也许你们知道我怎样才能让它不那么麻烦?如何避免在内部使用定义并命名这么多变量?

最佳答案

import fractions
print fractions.gcd(4,8)
>>> 4

不过你也可以看看源码:

def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.

Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a

引用:http://en.wikipedia.org/wiki/Euclidean_algorithm

关于python - 找出最大公约数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14231406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com