python最大公約數
1. 怎麼用遞歸實現求最大公約數(python)
def gcd(a, b):
if a % b == 0:
return b
else:
return gcd(b, a % b)
2. Python 求2~4個數的最大公約數
defGreatCommonDiv(numbers):
mx=rece(lambdax,y:max(x,y),numbers)
whileTrue:
flag=True
fornumberinnumbers:
ifnumber%mx!=0:
flag=False
break
ifflag==True:
returnmx
mx-=1
if__name__=="__main__":
#測試
print(GreatCommonDiv([1,2,3,4,5]))
print(GreatCommonDiv([12,24,18,8]))
print(GreatCommonDiv([128,256,192]))
#測試結回果答
#1
#2
#64
3. python 遞歸演算法算最大公約數
設計的邏輯就有問題,find就該做find的事,不要在find里有輸出
#yourcodegoeshere
defGCD():
b=input("pleaseenterthefirstnumber")
c=input("pleaseenterthesecondnumber")
printfind(b,c)
deffind(b,c):
ifb>c:
d=b%c
b=c
ifd==0:
returnb
c=d
find(b,c)
else:
e=c%b
c=b
ife==0:
returnc
b=e
find(b,c)
#printfind(b,c)
defsimp_find(b,c):
ifb%c!=0:
returnsimp_find(c,b%c)
returnc
GCD()
4. python 求最大公約數
最大公約數這個我不懂,你還是上網上搜一搜吧!
5. Python任意輸入兩個數,求兩個數的最大公約數(最大公約數條件是公約數
# 定義一個函數
def hcf(x, y):
"""該函數返回兩個數的最大公約數"""
# 獲取最小值
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
# 用戶輸入兩個數字
num1 = int(input("輸入第一個數字: "))
num2 = int(input("輸入第二個數字: "))
print( num1,"和", num2,"的最大公約數為", hcf(num1, num2))
6. python中求最大公約數
就是y 非0的時候一直做
你也可以寫成 y != 0
我也建議你寫成 y!= 0
這樣程序的可讀性更好
7. python求最大公約數
要是我真想說沒法打,一個一個答案不能完全統一,要求都一樣吵。
8. 最大公約數python代碼
嗯嗯最大的公約數匹配的代碼應該是從他的技術開始算起,然後通過共計數額進行解答。
9. Python怎樣求得最大公約數
核心代碼很簡單:
def gcd(a, b):
if b == 0:return a
return gcd(b, a % b)
附上一個用Python實現求最大公約數同時判斷是否是素數的一般方法:
程序如下:
#!/usr/bin/env python
def showMaxFactor(num):
count = num / 2
while count > 1:
if num % count == 0:
print 'largest factor of %d is %d' % (num, count)
break #break跳出時會跳出下面的else語句
count -= 1
else:
print num, "is prime"
for eachNum in range(10,21):
showMaxFactor(eachNum)
輸出如下:
largest factor of 10 is 5
11 is prime
largest factor of 12 is 6
13 is prime
largest factor of 14 is 7
largest factor of 15 is 5
largest factor of 16 is 8
17 is prime
largest factor of 18 is 9
19 is prime
largest factor of 20 is 10
10. python求最大公約數和最小公倍數
a,b=map(int,input().split())
a1,b1=a,b
res=a1%b1
whileres!=0:
a1=b1
b1=res
res=a1%b1
print(str(b1)+''+str(a*b/b1))#前面最大公約數,後面最小回公倍答