If, for example, I have a nesting function like

Nest[1 + x^n (#) &, 1, 3]

it gives the result

1 + x^n (1 + x^n (1 + x^n))

I would need the n to increase by one with every step, just like in a sum or product function, so that the result would be

1 + x^1 (1 + x^2 (1 + x^3))

Is there a way to do this in Mathematica? If so, how?

  • Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Michael E2 Dec 5 '15 at 2:40
up vote 7 down vote accepted
Module[{i = 1}, Nest[1 + x^n (#) &, 1, 3] /. n :> i++]

enter image description here

Or (same result)

Fold[1 + x^#2 #1 &, 1, {3, 2, 1}]
  • +1 for Module construct. – garej Dec 5 '15 at 11:48

Taking a different approach it appears that you are seeking to apply Horner's Method to the polynomial

$$\underset{i=0}{\overset{n}{\sum }}x^{\underset{j=0}{\overset{i}{\sum }}j}$$

Taking $\underset{j=0}{\overset{i}{\sum }}j = \frac{1}{2}i(1+i)$ and making use of HornerForm a function can be created to construct the factored polynomial.

f[n_Integer?Positive] := HornerForm@Sum[x^(i (1 + i)/2), {i, 0, n}]

You are seeking f[3]

f[3]
(* 1 + x (1 + x^2 (1 + x^3)) *)

Hope this helps.

In case the intermediate result 1 + x^n (1 + x^n (...)) is not required,

n = 3;
First@Nest[{1 + x^#[[2]] #[[1]], #[[2]] - 1} &, {1, n}, n]

Alternative

A simpler formulation under the same assumption as above

n = 3;
Nest[1 + x^(n--) # &, 1, n]
  • +1 for (n - -) construct – garej Dec 5 '15 at 11:49

I would use Fold.

Fold[1 + x^#2 (#1) &, 1, Range[3, 1, -1]]
(*  1 + x (1 + x^2 (1 + x^3))  *)

Two approaches with Replacement.


z = Nest[1 + x^n (#) &, 1, 3]
ReplacePart[z, Position[z, n][[#]] -> Defer@# & /@ Range[3]]

enter image description here


Also inspired by the @Karsten7's answer and @Eldo's Module version:

Module[{r = 3, i = 1}, 
Quiet@ReplaceRepeated[(1 + x^n), (1 + x^n) -> 1 + x^n (1 + x^n), 
MaxIterations -> r - 1] /. n :> i++]

1 + x (1 + x^2 (1 + x^3))

  • 1
    Some more inspiration: Module[{n = 3}, ReplaceRepeated[(1 + x^n), p_Plus /; n > 1 :> 1 + x^(--n) p]] – Karsten 7. Dec 5 '15 at 16:58

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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