我正在尝试寻找最大公因数。
我编写了一个糟糕的算法(操作密集型),它将较小的值减一,使用%检查是否可以均匀地分配分子和分母,如果可以,则退出程序。然而,我的while循环没有使用and运算符,因此一旦分子可被整除,它就停止了,即使它不是正确的答案。
我使用的数字是54和42,正确的GCD(最大公约数)为6。
我得到的答案是27,这告诉我一旦它达到27并且可以平均分割54/27,它就会停止。有没有关于如何在Python中在while循环中使用and运算符的想法?
谢谢!
我编写了一个糟糕的算法(操作密集型),它将较小的值减一,使用%检查是否可以均匀地分配分子和分母,如果可以,则退出程序。然而,我的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运算符的想法?
谢谢!
or
。 - Mark Byers