【发布时间】:2017-10-23 05:46:14
【问题描述】:
我们需要向用户询问 (1) 测试用例的数量,以及 (2) 组成分数的两个整数(我将其作为 a:numerator 和 b:denominator 进行)。那么我们需要以这种形式(1/2 + 1/y)打印该分数。另外,我们必须使用 gcd 函数来编写我们的代码
we were given a couple of sample inputs to check our work:
- input 2 and 3 must output '1/2+1/6'
- input 1 and 4 must output '1/2+1/-4'
- input 7 and 10 must output '1/2+1/5'
- input 1 and 1 must output '1/2+1/2'
这是我的代码:
N = int(input())
index = 1
while index<=N:
a = int(input())
b = int(input())
num = 2*a -b
den = 2*b
def gcd(x,y): #this calculates for the greatest common divisor
if x>y:
smaller=y
else:
smaller=x
for factor in range(1,smaller+1):
if (x%factor==0) and (y%factor==0):
hcf=factor #this is the gcd
newNum=num//hcf
newDen=den//hcf
newFrac=str(newNum)+'/'+str(newDen) #to simplify the fraction, both numerator and denominator are divided by the gcd
print('1/2+'+newFrac)
index = index + 1
gcd(num,den)
在尝试运行代码时,有一些输入可以提供我想要的结果,但有些输入却没有...我的代码有什么问题?我应该在某处打断线吗?
sample input # and what they output (in comments)
4 # number of test cases
2
3
#outputs 1/2+1/6 ---> correct
1
4
#outputs nothing ---> incorrect
7
10
#outputs 1/2+4/20
# 1/2+2/10
# 1/2+1/5 ---> outputs too much ---> incorrect
1
1
#outputs 1/2+1/2 ---> correct
提前致谢! :)
【问题讨论】:
标签: python greatest-common-divisor number-theory