# Efficiently strip off coefficients in front of variables?

I am working with multivariate polynomials and need a very efficient way to decompose monomials into coefficients and pure monomials. for instance consider variables x and x and the monomial

monomial = C1 x x^2;


To get just the coefficient efficiently, I can do:

coefficient = monomial /.x[_]->1;


Then, to obtain the pure monomial without the coefficient, until now I have been doing:

puremonomial = monomial/coefficient;


However, as the coefficient grows larger in complexity (depending on a sum over rational expressions in many unfixed parameters), this seemingly trivial division takes Mathematica longer and longer to perform. (Having an iteration in place that has to perform this operation several thousand times, makes the code slow.) Therefore, I wonder if there is a command that would strip off the coefficient in front of a monomial efficiently, regardless of its complexity? So, I would like a function:

pureMonomial[monomial_,variables_]


such that

pureMonomial[monomial,{x,x}]


xx^2

does not slow down with growing size of C1. Any suggestions?

• What about: Replace[monomial, coef_ t : Times[Power[x[_], _.] ..] :> (1 t)] ? – user31159 Apr 1 '16 at 18:46
• Or Replace[expr, Times[Except[_x, _], l_] :> (1 l)] ? – user31159 Apr 1 '16 at 18:50
• @Xavier. That's fast. I suggest posting it as a solution! (After verifying robustness, maybe.) – march Apr 1 '16 at 19:02
• @Kagaratsch, maybe just monomial /. (monomial /. x[_] -> 1) -> 1 – garej Apr 1 '16 at 19:29

## 2 Answers

Replace[monomial, coefs_ t : Times[Power[_x, _.] ..] :> {coefs, 1 t}]


Examples:

Replace[C1 x x^2, coefs_ t : Times[Power[_x, _.] ..] :> {coefs, 1 t}]

(* {C1, x x^2} *)

Replace[C1 C2 x x^2 x, coefs_ t : Times[Power[_x, _.] ..] :> {coefs, 1 t}]

(* {C1 C2, x x^2 x} *)


An approach that generalizes to polynomials:

splitpoly[poly_, vars_] := Module[{
cl = CoefficientList[poly, vars]},
{Extract[cl, #], Times @@ (vars^(# - 1))} & /@
Position[cl, Except, {-1}, Heads -> False] ]

splitpoly[1 + C0 x + C1 x x^2, {x, x}]


{{1, 1}, {C0, x}, {C1, x x^2}}

recover the polynomial:

 Times @@@ % // Total


1 + C0 x + C1 x x^2