[英]Greatest Common Divisor (GCD)
def get_divs(z):
return [i for i in range(1, z) if z % i == 0]
def gcd(x, y):
x_div=get_divs(x)
y_div=get_divs(y)
cd=set(x_div).intersection(y_div)
gcd=cd[-1]
print("The GCD of",x,"and",y,"is",gcd)
return 1
我試圖讓這個程序計算兩個用戶輸入的正整數(x 和 y)的最大公約數 (GCD)。 集合 function 不返回可以索引的列表。 關於如何找到 GCD 有什么建議嗎?
很抱歉 5 年后才回復。 但是您可以使用歐幾里得算法找到 GCD。 這是代碼:
a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
r = a%b
while (r!=0):
a=b
b=r
r = a%b
print(f'greatest common divisor is {b}')
這是算法的外觀。
findGCD(int firstNum, int secondNum){
int smaller; int bigger;int remainder;
if(firstNum < secondNum) {
smaller = firstNum;
bigger = secondNum;
}
else {
smaller = secondNum;
bigger = firstNum;
}
while(true) {
remainder = bigger % smaller;
if(remainder == 0) {
break;
}
else {
bigger = smaller;
smaller = remainder;
}
}
return smaller;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.