# Implementation of a recursive function [duplicate]

I have been trying to implement a recursive function, but still struggle. Here's what I have written:

Subscript[p, n_] := Subscript[p, n - 1] + (n + 1)*x^n

Subscript[p, 1] = 1


And executing

Subscript[p, 4]


I get

1 + 3 x^2 + 4 x^3 +5 x^4


Now, I tried to define:

Polynom[x_] := Subscript[p, 4]


However, when I try to evaluate

Polynom[4]


I still get the result:

1 + 3 x^2 + 4 x^3 + 5 x^4


So Mathematica didn't replace x with 2 . Can anyone explain to me why or how I can define the function I want so it evaluates for Polynom[4]?

## marked as duplicate by Mr.Wizard♦Jan 8 '15 at 5:04

• Your definition of Polynom[x_] does not involve any variable x on the right-hand side, it merely assigns all values of Polynom to the single constant value Subscript[p,4]. You seem a novice with Mathematica notation, function definition, etc. – David G. Stork Jan 8 '15 at 1:10
• Related: (8829), (70030) – Mr.Wizard Jan 8 '15 at 5:04
• Please see the link below "This question already has an answer here:" at the top of your question as well as the "Related:" links directly above. In this case you could simply define Polynom[x_] = Subscript[p, 4]; but it is very important that you understand why this works and its limitations. After reading those Q&A's please let me know if it remains unclear. – Mr.Wizard Jan 8 '15 at 5:08

f[x_, n_] := f[x, n - 1] + (n + 1)*x^n

f[x_, 1] = 1;

polynom[x_] := f[x, 4]

polynom@4  (*1585*)


If I understand your purpose correctly,

$$a_{m,n}=a_{m,n-1}+(n+1)m^n$$

I propose using Nest to implement this recursive formula.

$$\{a_{m,n-1},m,n-1\} \Rightarrow \{f(a_{m,n-1},m,n-1),m,n\}$$

where

$$f(x,y,z)=x+(z+2)y^{(z+1)}$$

a[m_,n_,val_]:=
First@
Nest[{#1 + (#3 + 2) #2^(#3 + 1), #2, #3 + 1} & @@ # &, {val, m, 1}, m-1]


where val is the value of $a_{m,1}$

 a[4, 1, 1]
(*1585*)