6
$\begingroup$

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[2] y[3] + 6 y[2] y[4] + 12 y[3] y[4] + 8 y[2] y[5] + 16 y[3] y[5] + 24 y[4] y[5]

which yields for the length

Length[poly]
6

Similarly for $n=4$

n = 4; poly
4 y[2] y[3] + 6 y[2] y[4] + 12 y[3] y[4]

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[2] y[3]

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!

$\endgroup$

1 Answer 1

8
$\begingroup$

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[96]:= poly = 4 y[2] y[3]

Out[96]= 4 y[2] y[3]

In[97]:= CoefficientRules@poly

Out[97]= {{1, 1} -> 4}

In[98]:= Length@CoefficientRules@poly

Out[98]= 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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.