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!
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With