简体   繁体   English

Python While循环,和(&)运算符不起作用

[英]Python While Loop, the and (&) operator is not working

I am trying to find the greatest common factor. 我试图找到最大的共同因素。

I wrote a bad (operation intensive) algorithm that decrements the lower value by one, checks using % to see if it evenly divides both the numerator and denominator, if it does then it exits the program. 我编写了一个糟糕的(操作密集型)算法,将较低的值减1,检查使用%来查看它是否均匀地除以分子和分母,如果它然后它退出程序。 However, my while loop is not using the and operator, and thus once the numerator is divisible it stops, even though its not the correct answer. 但是,我的while循环不使用和运算符,因此一旦分子可被整除,它就会停止,即使它不是正确的答案。

The numbers I am using are 54 and 42, the correct GCD (greatest common denominator) is 6. 我使用的数字是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

The answer I am getting is 27, which tells me once it reaches 27 and can divide 54/27 evenly, it stops. 我得到的答案是27,它告诉我一旦达到27并且可以均匀地划分54/27,它就会停止。 Any thoughts on how to use an and operator in a while loop in python? 有关如何在python中使用while循环中的和运算符的任何想法?

Thanks! 谢谢!

You should be using the keyword and instead of the bitwise and operator & : 您应该使用关键字and不是按位和运算符&

while (v % d != 0) and (u % d != 0): 

This is also the same: 这也是一样的:

while (v % d) and (u % d): 

Note that & and and will give the same result in the first case, but not in the second. 需要注意的是&并且and第二会产生相同的结果在第一种情况下,但不是。

Your problem though is that you want to use or instead of and . 你的问题是,你想使用or代替and Also your algorithm is highly inefficient. 您的算法也非常低效。 There are better ways to calculate the GCD . 更好的方法来计算GCD

Use the and keyword. 使用and关键字。 & is a bitwise and operator. &是一个按位和操作员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM