# Factor polynomial with specific common variables (terms)

I want to factor the following polynomial:

b*p - b*q + c*q - c*r - a*(p - r)


When I use the function FactorTerms. I get the following result:

FactorTerms[b*p - b*q + c*q - c*r - a*(p - r), {p, q, r}]
// Output: (-a)*p + b*p - b*q + c*q + a*r - c*r

FactorTerms[b*p - b*q + c*q - c*r - a*(p - r), {a, b, c}]
// Output: (-a)*p + b*p - b*q + c*q + a*r - c*r


Using simplify actually gives me factors:

Simplify[b*p - b*q + c*q - c*r - a*(p - r)]
// Output: b*(p - q) + c*(q - r) + a*(-p + r)


The only problem is that I wanted the common terms to be p, q and r.

How can I tell Mathematica to factor a polynomial with specific common variables?

Thanks.

• The Simplify result shows a sum, not a product. This is not going to be amenable to factorization. May 3 '20 at 14:42

You can use Collect here.

Collect[b*p - b*q + c*q - c*r - a*(p - r), {p, q, r}]


(-a + b) p + (-b + c) q + (a - c) r

It will also work for {a, b, c} as above. Also another fun thing with Collect. We can apply Factor to each coefficient obtained for {p,q,r} and I tweaked your polynomial a bit so p has a coefficient that can be factored.

Collect[b^2*p - b*q + c*q - c*r - a^2*(p - r), {p, q, r}, Factor]


-(a - b) (a + b) p + (-b + c) q + (a^2 - c) r

• Thanks PlatoManiac. I knew Mathematica has such a function. Couldn't just figure out its name. May 3 '20 at 7:42
• I have a question. Why does FactorTerms expands all the terms instead of combining some of them in the above case? May 3 '20 at 7:43
• I guess this is a planned design choice. Collect gives us lots of more power how we would like to combine our preferred terms in a polynomial. I gave an example above. By the way you should wait before accepting answers. This will inspire others to also contribute new answers sometimes :) May 3 '20 at 7:48
• Thanks @PlatoManiac. :) May 3 '20 at 20:49