# Counting the number of terms in a polynomial using Length command

I have the following polynomial which depends on $n$:

poly = (Sum[(i - 1) y[i], {i, 1, n, 1}])^2  - Sum[(i - 1)^2 y[i]^2, {i, 2, n, 1}] // Expand;


The Mathematica Length command can be used to determine the length of poly for an arbitrarily chosen value of $n$.

For instance for $n=5$:

n=5; poly

4 y y + 6 y y + 12 y y + 8 y y + 16 y y + 24 y y


which yields for the length

Length[poly]

6


Similarly for $n=4$

n = 4; poly

4 y y + 6 y y + 12 y y


which yields for the length

Length[poly]

3


But here comes the problem. For $n=3$, poly takes the following form

n = 3; poly

4 y y


which yields for the length

Length[poly]

3


as opposed to 1. Since there is now only 1 term, it is counting each sub-term and taking that to be the length. What could be done to correct for this? I need it to only count the total number of terms for all values of $n$. Thank you!

I was going to suggest manipulating heads and checking the length of arguments under the head Plus, but then I realized that Length[CoefficientRules[poly]] does the job nicely.

In:= poly = 4 y y

Out= 4 y y

In:= CoefficientRules@poly

Out= {{1, 1} -> 4}

In:= Length@CoefficientRules@poly

Out= 1


Alternatively you can do

Length[poly + Unique["x"]] - 1


which will ensure a head of Plus around the expression whose length is being checked.

• +1 However, in general the second solution would need to include Expand: Length[Expand[poly] + Unique["x"]] - 1 – Bob Hanlon Aug 19 '15 at 12:42