我试图找到最大的公因数。
我写了一个糟糕的(操作密集型)算法,将较低的值减一,使用 % 检查它是否将分子和分母均分,如果是,则退出程序。但是,我的 while 循环没有使用 and 运算符,因此一旦分子可整除,它就会停止,即使它不是正确的答案。
我使用的数字是 54 和 42,正确的 GCD(最大公分母)是 6。
#heres a simple algorithm to find the greatest common denominator:
iterations = 0; #used to calculate number of times while loop is executed
u = 54; v= 42; d = v-1; #u is the numerator, v is the denominator, d is the number decremented by one
while ((v % d !=0) & (u % d != 0)): #while both numerator AND denominator cannot be evenly divided by the decremented number
d -= 1 #decrement the number by one
print d #print the number decremented
iterations +=1 #add 1 to the count of iterations in while loop
print "the gcd is " +str(d) #should be 6 when the number can evenly divide both
print "the number of iterations was " +str(iterations) #display times it took algorithm to complete
我得到的答案是 27,它告诉我一旦达到 27 并且可以平均划分 54/27,它就会停止。关于如何在python的while循环中使用and运算符有什么想法吗?
谢谢!