Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute recursion relations in mathematica efficiently?

I have a recursion to solve for.

f(m,n)=Sum[f[m - 1, n - 1 - i] + f[m - 3, n - 5 - i], {i, 2, n - 2*m + 2}] + f[m - 1, n - 3] + f[m - 3, n - 7]
f(0,n)=1, f(1,n)=n

However, the following mma code is very inefficient

f[m_, n_] := Module[{},
  If[m < 0, Return[0];];
  If[m == 0, Return[1];];
  If[m == 1, Return[n];];
  Return[Sum[f[m - 1, n - 1 - i] + f[m - 3, n - 5 - i], {i, 2, n - 2*m + 2}] + f[m - 1, n - 3] + f[m - 3, n - 7]];]

It takes unbearably long to compute f[40,20]. Could anyone please suggest an efficient way of doing this? Many thanks!

like image 337
Qiang Li Avatar asked Jan 12 '11 02:01

Qiang Li


1 Answers

Standard trick is to save intermediate values. The following takes 0.000025 seconds

f[m_, n_] := 0 /; m < 0;
f[0, n_] := 1;
f[1, n_] := n;
f[m_, n_] := (f[m, n] = 
    Sum[f[m - 1, n - 1 - i] + f[m - 3, n - 5 - i], {i, 2, 
       n - 2*m + 2}] + f[m - 1, n - 3] + f[m - 3, n - 7]);
AbsoluteTiming[f[40, 20]]
like image 100
Yaroslav Bulatov Avatar answered Sep 22 '22 10:09

Yaroslav Bulatov