# Factorize in a particular way

I was trying to factorise this polynomial expression:

TestPolynomial=-p1^2 x1 x2 - p3^2 x1 x3 - p1^2 x2 x3 + 2 p1 p3 x2 x3 - p3^2 x2 x3


into this form,

-p1^2 x1 x2 - p3^2 x1 x3 - (p1-p3)^2 x2 x3


However, when we use Simplify[], we obtain

2 p1 p3 x2 x3 - p3^2 (x1 + x2) x3 - p1^2 x2 (x1 + x3)


How can I say Mathematica that I wish to get the polynomial factorised in terms of variables (p1,p3).

Try this:

xvars={x1,x2,x3};
FromCoefficientRules[CoefficientRules[TestPolynomial,xvars]//Factor,xvars]


This is based on the following interpretation of your question: View the expression as a polynomial in x1, x2, x3 with coefficients that are polynomials in p1, p2, p3 and simplify those coefficients. I use CoefficientRules since that is a very useful command in many situations.

A quick way to do that is:

Collect[TestPolynomial,{x1,x2,x3},Simplify]


An inconvenience with the above code is that it also factorizes some of the variables :

output : -(p1 - p3)^2 x2 x3 + x1 (-p1^2 x2 - p3^2 x3)

If you prefer that the code only simplifies the coefficients, a solution is to take a symbol without an assigned value, say g, then enter the code (see footnote *tip below for a tip):

Expand@Collect[TestPolynomial,{x1,x2,x3},g@*Simplify] /.g->Identity


If you are looking for speed, at least for the example you gave, the code above is about 3 times faster than the one provided by @user293787 on my computer.

*tip: to be sure that the symbol will not be assigned a value in the future, you can use

\[FormalG]


(type the Esc key then the \$ key or . key then g (or another letter) then the Esc key again ).

\[FormalG] is protected by default so it will not be assigned a value (maybe unless someone uses Unprotect but I have personally avoided using Unprotect)