5

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?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Yukterez
  • 488
  • 4
  • 14
  • 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 05 '15 at 02:40

5 Answers5

7
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}]
eldo
  • 67,911
  • 5
  • 60
  • 168
6

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.

Edmund
  • 42,267
  • 3
  • 51
  • 143
5

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]
3

I would use Fold.

Fold[1 + x^#2 (#1) &, 1, Range[3, 1, -1]]
(*  1 + x (1 + x^2 (1 + x^3))  *)
Eric Towers
  • 3,040
  • 12
  • 14
2

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))

garej
  • 4,865
  • 2
  • 19
  • 42
  • 1
    Some more inspiration: Module[{n = 3}, ReplaceRepeated[(1 + x^n), p_Plus /; n > 1 :> 1 + x^(--n) p]] – Karsten7 Dec 05 '15 at 16:58