在满足条件之前,我该如何重复“ if”语句?

时间:2019-08-22 02:23:43

标签: python

我正在尝试制作一个运行Euclidian算法的python程序。这是我当前的代码:

a = float(input())
b = float(input())
aplha = float(a/b)
omega = float(b/a)

import math
if a > b:
    print(str(a) + " = " + str(b) + " * " + str(math.floor(aplha)) + " + " + str(a%b)) 
elif b > a:
    print(str(b) + " = " + str(a) + " * " + str(math.floor(omega)) + " + " + str(b%a)) 
else:
    print("Both numbers have the same value. The greatest common denominator is 1.")

如何使if和elif不断重复直到a%b = b%a = 0?

1 个答案:

答案 0 :(得分:0)

这是实现欧几里得算法的一种方法。

import math

a = float(input())
b = float(input())

# The greatest common denominator of a and b
def gcd(a,b):
    while (b != 0):
       t = b
       b = a % b
       a = t 
    return a

if (a > b):
    print(f'{a} = {b} * {math.floor(a/b)} + {a%b}')
else:
    print(f'{b} = {a} * {math.floor(b/a)} + {b%a}')


print(f'The greatest common denominator of {a} and {b} is {gcd(a,b)}')

如果a==b不一定是GCD为1。考虑将a = 150b = 150作为反例。 ab的最大公分母为150。gcd(a,b) = 150

另请注意print(f'string{var}')。 Print f-string是Python 3中的新增功能,对于打印变量值确实很有帮助。运作方式是

>>> var = 5
>>> print(f'The value of var is {var}')
"The value of var is 5"