7

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!

2 Answers 2

22

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for input, I tried using the keyword and, but I still got 27, are you getting the same result?
@Blakedallen: Try using or.
You are correct this is highly inefficient! I believe Euclid's algorithm is much better.
1

Use the and keyword. & is a bitwise and operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.