我正在编写一个程序来使用欧几里得算法计算两个给定整数的最大公约数(GCD)。输入包含两个正整数 x 和 y,由空格分隔。当输入 0 0 时,程序终止。我刚接触 Python,我绝对是编程的菜鸟,所以我的编码实践可能有点粗糙。我试图将计算出的 GCD 打印在与输入相同的行上。如何将该计算值打印到我输入两个整数的同一行?
输入完成后看起来像这样:
输入:
210 45 15
这就是我所能做的:
输入:
210 45
15
到目前为止,我有此代码用于 python 2.7:
def gcd (x, y): # Greatest Common Divisor function
if x > y:
r = x%y # r = x divided by y and gives the remainder
if r == 0: # if the division of x and y has no remainder, return y because y is the gcd.
return y #This is true because no number may have a divisor greater than the number itself (non-negative).
else:
return gcd(y, r) #if a = bt+r, for integers t and r, then gcd(x,y) = gcd(b,r)
if x < y:
x, y = y, x # value swapping
return gcd(x, y)
getinput = True
while(getinput):
#list created for storing user entered values
ssplit = []
s = raw_input('Input: \n ') # read a string of data, no evaluation by python
ssplit = s.split(' ') # read values between whitespace
x = int(ssplit[0]) # place value from raw_input() into list
y = int(ssplit[1])
if( x != 0 and y != 0 ): #tests to see if gcd needs to be evaluated
print (gcd (x, y))
else:
getinput = False # input was 0 0