问题
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. 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.
The numbers I am using are 54 and 42, the correct GCD (greatest common denominator) is 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. Any thoughts on how to use an and operator in a while loop in python?
Thanks!
回答1:
You should be using the keyword and
instead of the bitwise and operator &
:
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.
Your problem though is that you want to use or
instead of and
. Also your algorithm is highly inefficient. There are better ways to calculate the GCD.
回答2:
Use the and
keyword. &
is a bitwise and operator.
来源:https://stackoverflow.com/questions/10764007/python-while-loop-the-and-operator-is-not-working