pythonwhile not_Python While循环中,and(&)运算符不起作用

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!

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值