欧氏算法的理解

时间:2018-12-04 16:03:49

标签: python

当我使用数字931和301时,它正确地显示为7。但是我不明白为什么while函数不会更早终止。最后一步,变量看起来像r0 = 7,r1 = 0和r2 = 0。它们之前的步骤应该是r0 = 21,r1 = 7和r2 = 0。因此r2为0,而while函数不应再计算一个stept,而实际上r1 = 7应该是bcd而不是r0。感谢您的帮助。

python代码:

print('find biggest common divisor')
print('bigger number:')
r0 = input()
print('smaller number:')
r1 = input()
r0 = int(r0)
r1 = int(r1)
r2 = 1
while r2 != 0:    
    r2 = r0 % r1
    r0 = r1
    r1 = r2
print('bcd is ' + str(r0))

2 个答案:

答案 0 :(得分:4)

您输入的值有误。上一步中的r27

...
while r2 != 0:    
    r2 = r0 % r1
    r0 = r1
    r1 = r2
    print("r0: " + str(r0) +", r1: " + str(r1) + ", r2: " + str(r2))
print('bcd is ' + str(r0))

输出:

find biggest common divisor
bigger number:
931
smaller number:
301
r0: 931, r1: 301, r2: 1
r0: 301, r1: 28, r2: 28
r0: 28, r1: 21, r2: 21
r0: 21, r1: 7, r2: 7
r0: 7, r1: 0, r2: 0
bcd is 7

答案 1 :(得分:0)

非常感谢!这是我的第一个程序,很抱歉,我没有看到简单的解决方案,只是打印出值以查看错误。以下工作与现在预期的一样。

print('find biggest common divisor')
print('bigger number:')
r0 = input()
print('smaller number:')
r1 = input()
r0 = int(r0)
r1 = int(r1)
r2 = r0 % r1
# print("r0: " + str(r0) +", r1: " + str(r1) + ", r2: " + str(r2))
while r2 != 0:
    r0 = r1    
    r1 = r2
    r2 = r0 % r1
    # print("r0: " + str(r0) +", r1: " + str(r1) + ", r2: " + str(r2))
print('bcd is ' + str(r1))