如何在python上将一个分数拆分为两个分数?
我们需要向用户询问(1)测试用例的数量,以及(2)组成分数的两个整数(我是作为a:分子和b:分母做的)。然后我们需要以这种形式打印分数(1/2+1/y)。此外,我们必须在编写代码时使用gcd函数如何在python上将一个分数拆分为两个分数?,python,greatest-common-divisor,number-theory,Python,Greatest Common Divisor,Number Theory,我们需要向用户询问(1)测试用例的数量,以及(2)组成分数的两个整数(我是作为a:分子和b:分母做的)。然后我们需要以这种形式打印分数(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
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)
提前感谢!:) 您可以尝试以下方法:
N = int(input())
for __ in range(N):
a = int(input())
b = int(input())
a_b_str = ('%i/%i' %(a,b)).ljust(5) # for printout purposes; optional
num = 2*a - b
den = 2*b
if num == 0:
print(a_b_str + ' --> 1/2')
elif den % num == 0:
y = den / num
print(a_b_str + ' --> 1/2+1/%i' %y)
else:
print(a_b_str + ' CAN NOT BE REPRESENTED IN THE FORM: "1/2+1/y"')
结果:(分别针对a、b)
实际上,你不需要为你的任务做很多事情,因为:
a/b = 1/2 + 1/y
=> 1/y = a/b - 1/2
=> 1/y = (2*a - b) / 2*b
=> y = 2*b / (2*a - b) = den / num
UPD。
替代解决方案-使用gcd():
可能重复我应该在原始问题中指定它,但我们需要使用gcd函数来编写代码…谢谢,但我没有意识到是这样simple@user8638151,检查最后一次编辑-是否符合要求?
2/3 --> 1/2+1/6
1/4 --> 1/2+1/-4
7/10 --> 1/2+1/5
1/1 --> 1/2+1/2
1/2 --> 1/2
1/5 CAN NOT BE REPRESENTED IN THE FORM: "1/2+1/y"
3/2 --> 1/2+1/1
5/2 CAN NOT BE REPRESENTED IN THE FORM: "1/2+1/y"
-1/2 --> 1/2+1/-1
-1/4 CAN NOT BE REPRESENTED IN THE FORM: "1/2+1/y"
a/b = 1/2 + 1/y
=> 1/y = a/b - 1/2
=> 1/y = (2*a - b) / 2*b
=> y = 2*b / (2*a - b) = den / num
# gcd based on Euclid's algorithm
def gcd(b, a):
while a:
b, a = a, b%a
return abs(b)
N = int(input())
for __ in range(N):
a = int(input())
b = int(input())
a_b_str = ('%i/%i' %(a,b)).ljust(5)
num = 2*a - b
den = 2*b
if num == 0:
print(a_b_str + ' --> 1/2')
else:
gcd_temp = gcd(den, num)
if gcd_temp == abs(num):
y = (num/gcd_temp) * (den/gcd_temp)
print(a_b_str + ' --> 1/2+1/%i' %y)
else:
print(a_b_str + ' CAN NOT BE REPRESENTED IN THE FORM: "1/2+1/y"')