I have written a recursive function and would like to re-write the code using Module AND While to compare the timings.
Here is my recursive function for f[n], where 6 n f[n] = f[n-1] + n! for n>0 and f[0]=7.
Clear[f]
f[0] = 7;
f[n_Integer /; n>0] := f[n-1]/(6 n) + n!
Now I want to write it using Module AND While, I could write using Module ONLY, but I am struggling when I need to combine it using While loop.
Here is my code using Module only:
fm[n_] := Module[{f}, f[0] = 7; f[i_] := f[i-1]/(6 i) + i!; f[n]]
Then if I want to use Module AND While, I get into trouble, here is my code:
fm[n_] := Module[{fw}, While[n>=0, fw[0] = 7; fw[i_] := fw[i-1]/(6 i); fw[n] ] ]
The code is not working and I couldn't figure out where does it go wrong. Do I still need to write recursively inside the While loop? And how could I write the correct code?
Any detailed explanations are greatly appreciated. Thanks in advance!
Ctrl
+K
to format it as such. $\endgroup$f[n-1] / (6 n)
etc. instead of TeX. $\endgroup$