# Collect/Factor a fraction

Is there a way to tell Mathematica to factor things only containing a specific combination of a fraction, example:

$$\tag{1}f = \frac{a+m\cdot a+b+n\cdot b+c+k\cdot c+d+e}{ab}$$

Is there a way to make Mathematica rewrite $(1)$ as

$$f = \frac{1+n}{a}+\frac{1+m}{b} +\frac{c(1+k)+d+e}{ab}\,~~~~~~~?$$

expr = (a + m a + b + n b + c + k c + d + e)/(a b);


This gets us almost where we want to go,

Expand@expr
(* 1/a + 1/b + c/(a b) + d/(a b) + e/(a b) + (c k)/(
a b) + m/b + n/a *)


But we have too many terms with the same denominator, so we can use GatherBy to group them, then simplify the sums of terms with the same denominator, then sum it all back up,

Together@*Plus @@@ GatherBy[List @@ Expand[expr], Denominator] // Total
(* (c + d + e + c k)/(a b) + (1 + m)/b + (1 + n)/a *)


But as OP points out, this will not combine terms where the denominator is the same except for a constant factor, like a/(2*b) and c/b. This function should be able to simplify an rational expression like desired in the OP (if you come up with a way to break the function, please let me know).

fractionExpand[expr_] :=
Replace[Expand@expr,
expr2_Plus :> (Together@*Plus @@@
GatherBy[List @@ expr2, Variables@*Denominator] // Total)]


This will break up a term into the largest number of fractions, without repeating denominators. Here are a few tests,

expr2 = (1 + m)/b + (1 + n)/a + (1 + o)/c + (d + e + f g)/(
a b) + (h + i + j k)/(b c) + (l + p q)/(a b c) // Together


fractionExpand@expr2


You get back the original input.

expr3 = a/(2 b) + c/b + d/e + f/(g + z) + (a - c)/(l m b) // Together


fractionExpand@expr3


• Wow, that was neat! – Your Majesty Apr 6 '16 at 13:04
• Now that I've played around with your code I notice that terms like 1/(2*b) and 1/(1*b) does not get written together. Your solution still answers the original question but perhaps I should've asked a more general question. Is there a simple way to fix this problem? – Your Majesty Apr 6 '16 at 15:17
• Can you give an example? fractionExpand[2/(1*b) + 2/c + 3/(2 b) + 4/(a b)] seems to work – Jason B. Apr 6 '16 at 15:23
• It would be nice if your code somehow differentiated between a variable name and a number such as 2. So that c/(2b)+1/b would read (c+2)/(2b). – Your Majesty Apr 6 '16 at 15:24
• will work on it, gotta leave for the day now though – Jason B. Apr 6 '16 at 15:25

I am not sure that this is better, but just as a version:

  expr1 = (a + m a + b + n b + c + k c + d + e);
expr2 = Collect[expr1, {a, b}];
expr3 = Take[expr2, 4];
Map[ReleaseHold,
MapAt[Hold, Take[expr2, {5, 6}]/(a*b), {{3, 1}, {3, 2}}] //
Apart] + expr3/(a*b)


(* (c + d + e + c k)/(a b) + (1 + m)/b + (1 + n)/a *)

Have fun!