Bla*_*len 7 python while-loop operator-keyword
我试图找到最大的共同因素.
我编写了一个糟糕的(操作密集型)算法,将较低的值减1,检查使用%来查看它是否均匀地除以分子和分母,如果是,则退出程序.但是,我的while循环不使用和运算符,因此一旦分子可被整除,它就会停止,即使它不是正确的答案.
我使用的数字是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
Run Code Online (Sandbox Code Playgroud)
我得到的答案是27,它告诉我一旦达到27并且可以均匀地划分54/27,它就会停止.有关如何在python中使用while循环中的和运算符的任何想法?
谢谢!
Mar*_*ers 18
您应该使用关键字and而不是按位和运算符&:
while (v % d != 0) and (u % d != 0):
Run Code Online (Sandbox Code Playgroud)
这也是一样的:
while (v % d) and (u % d):
Run Code Online (Sandbox Code Playgroud)
请注意,&并且and在第一种情况下会给出相同的结果,但在第二种情况下则不会.
你的问题是,你想用or而不是and.您的算法也非常低效.有更好的方法来计算GCD.
| 归档时间: |
|
| 查看次数: |
47275 次 |
| 最近记录: |