# Modify this code using Module and While

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=7.

Clear[f]
f = 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 = 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 = 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!

• user, I am repeating myself: please use proper code formatting and not LaTeX in a quote block. See editing help. While editing you can select the code and press Ctrl+K to format it as such. May 17, 2013 at 1:22
• @Mr.Wizard Thanks for your comment. But how can I write fractions without using Latex. I didn't seem to find any ways to do that in the editing help. May 17, 2013 at 1:27
• The point is to write code others can copy-paste into Mathematica. Write f[n-1] / (6 n) etc. instead of TeX. May 17, 2013 at 1:30

You mean this?

fw[i_Integer] := Module[{n = 0, last = 7}, While[++n <= i,
last = 1/(6 n) last + n!;
];
last]

• Thanks very much. It works. Your answer is very helpful. Now I have learned how to write in different ways. May 17, 2013 at 2:01

Since you are interested in learning different ways to write this, here is one that avoids using "variables" entirely, thus removing the need for Module:

fnw[i_Integer] :=
Last @ NestWhile[{# + 1, 1/(6 #) #2 + #!} & @@ # &, {1, 7}, #[] <= i &]


An expression such as #[] <= i & is a pure function with a single parameter represented by # (Slot). The expression {# + 1, 1/(6 #) #2 + #!} & @@ # & is two such functions strung together, with the longer one applied (@@) to the second, like this:

test = #/#2 & @@ # &;
test[{"a", "b"}]

"a"/"b"


This answer is also not direct answer because there is no Module or While but it is good to know that construct:

f[n_Integer /; n>0] := f[n] = f[n - 1]/(6 n) + n!
f = 7


More here