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)。 set函数不返回可以编制索引的列表。关于如何找到GCD的任何建议?
答案 0 :(得分:-1)
这是算法应该是什么样子。
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;
}