如何在python上将一个分数分成两个分数?

时间:2017-10-23 05:46:15

标签: 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 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
提前谢谢! :)

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

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

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

UPD。

替代解决方案 - 使用 gcd()

# 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"')