我正在尝试制作一个运行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?
答案 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 = 150
和b = 150
作为反例。 a
和b
的最大公分母为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"