# Recursion definition wont work [closed]

When I try use any function for example

f[n_] := n f[n – 1]

and then f[10]

I am getting error “Recursion depth of 1024 exceeded during evaluation of….” It seems it tries to compile negative values which is weird. How can I fix it?

=================

=================

2

=================

In addition to providing a terminating case, You can also use RSolve.

Clear[f, f1, f2]

f1[n_Integer?Positive] := f1[n] = n*f1[n – 1];
f1[0] = 1;

f2[n_] = f[n] /. RSolve[
{f[n] == n*f[n – 1], f[0] == 1},
f[n], n][[1]]

(* Pochhammer[1, n] *)

RSolve gives a result defined on a continuum rather than just for integer values of n.

Show[
Plot[f2[n], {n, -2, 4.2},
Exclusions -> {-1},
PlotRange -> {-10, 25}],
DiscretePlot[f1[n], {n, 0, 4},
PlotStyle -> Red]]

EDIT: Alternatively, from a sequence generated by f1, use FindSequenceFunction

f3[n_] = FindSequenceFunction[f1 /@ Range[10]][n]

(* n! *)

This is the same function as f2 and is defined for more than just integers

f3[n] == f2[n] // FullSimplify

(* True *)

Try

f[n_] := f[n]= n f[n – 1]
f[1]=1;

Then

f[5]
(* 120 *)

To understand how it works, type

?f

I though this program reads n as natural, but it seems to see it as integers which is weird (why integers and not for example reals?)
– tsin
Dec 19 ’15 at 20:27