Python While循环中,and (&)运算符无法工作

7
我正在尝试寻找最大公因数。
我编写了一个糟糕的算法(操作密集型),它将较小的值减一,使用%检查是否可以均匀地分配分子和分母,如果可以,则退出程序。然而,我的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运算符的想法?
谢谢!
2个回答

22
你应该使用关键字and而不是按位与运算符&:
while (v % d != 0) and (u % d != 0): 
这也是相同的内容:
while (v % d) and (u % d): 
请注意,在第一个情况下,&and将产生相同的结果,但在第二个情况下不会产生相同的结果。
你的问题是你想使用or而不是and。而且你的算法效率非常低下。有更好的方法来计算最大公约数,请参考这里

谢谢你的输入,我尝试使用了关键词"and",但是我仍然得到了27,你得到了相同的结果吗? - Blakedallen
@Blakedallen:尝试使用 or - Mark Byers
你说得对,这样做效率确实很低!我认为欧几里得算法要好得多。 - Blakedallen

1

使用 and 关键字。& 是按位与运算符。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接