Python While Loop, and (&) operator not working

I am trying to find the greatest common factor.

I wrote a bad (intensive) algorithm that reduces the lower value by one, checks the use of% to see if it divides both the numerator and the denominator evenly if it completes. However, my while loop does not use the and operator, and as soon as the numerator divides, it stops, although this is not the correct answer.

The numbers I use are 54 and 42, the correct GCD (largest 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 get is 27, which tells me when it reaches 27 and can divide 54/27 evenly, it stops. Any thoughts on how to use a and operator in a while loop in python?

Thanks!

+7
source share
2 answers

You should use the and keyword instead of the bitwise and operator & :

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

It is 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 is that you want to use or instead of and . Also your algorithm is extremely inefficient. There are better ways to calculate GCD .

+15
source

Use the and keyword. & is bitwise and operator.

0
source

All Articles