[英]How do I make a repeating 'if' statement until a condition is met?
I'm trying to make a python program that runs the Euclidian algorithm. 我正在尝试制作一个运行Euclidian算法的python程序。 This is my current code:
这是我当前的代码:
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.")
How do I make it so that the if and elif keeps repeating themselves until a%b
= b%a
= 0? 我如何使if和elif不断重复直到
a%b
= b%a
= 0?
Here is one way to implement the Euclidean algorithm. 这是实现欧几里得算法的一种方法。
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)}')
if a==b
it is not necessarily true that the GCD is one. 如果
a==b
,则GCD不一定为1。 Consider a = 150
and b = 150
as a counter example. 考虑
a = 150
和b = 150
作为反例。 The greatest common denominator of a
and b
is 150. gcd(a,b) = 150
. a
和b
的最大公分母为gcd(a,b) = 150
。
Also a note on print(f'string{var}')
. 还要注意
print(f'string{var}')
。 Print f-string is new in Python 3 and really helpful for printing the value of variables. Print f-string是Python 3中的新增功能,对于打印变量值确实很有帮助。 The way it works is
它的工作方式是
>>> var = 5
>>> print(f'The value of var is {var}')
"The value of var is 5"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.