# Iterating with Do rather than NestList

This code below works fine for me.

factor[x_] :=
Module[{i = 1},
NestList[Module[{result}, result = #*i; i = i + 2; result] &, 1,
x]];
factor[10]

{1, 1, 3, 15, 105, 945, 10395, 135135, 2027025, 34459425, 654729075}


But I wanna get it done with Do.

fat[x_] :=    Module[{i = 1},
Do[
Module[{result},
result = result*i; i = i + 2;
result
],
{x}
]
];
fat[9]


I failed to pull that off. It pops up \$RecursionLimit

• At each iteration you are creating result again and it does not have any initial value so you are essentially doing: ClearAll[x]; x = x + 1 – Kuba Jan 2 at 12:32
• @Kuba, How can you correct this? – kile Jan 2 at 12:44

## 2 Answers

Here is a way implement your function with Do.

f[n_] :=
Module[{result = 1, list = {1}},
Do[
result = result*i;
list = Join[list, {result}],
{i, 1, 2 n, 2}];
list]
f[5]


{1, 1, 3, 15, 105, 945}

• Isn't this essentially the same as my comment in the question? – Rohit Namjoshi Jan 2 at 16:38
• @RohitNamjoshi. The question doesn't have a comment made by you. – m_goldberg Jan 2 at 16:41
• Sorry, I meant my comment on Kuba's answer. – Rohit Namjoshi Jan 2 at 16:42
• @RohitNamjoshi. The two methods are similar, but since but since you posted your solution as a comment to another answer, I didn't see it. If you had written it as an answer (as I think you should have), I would likely not have posted my version. – m_goldberg Jan 2 at 16:48

At each iteration you are creating result again and it does not have any initial value so you are essentially doing:

ClearAll[x]; x = x + 1


Minor issue is that you don't have to manually increment i but use iterator spec {i, 1, 2 x - 1, 2}.

Moreover, if you insist on a procedural approach you need to switch to Table or Sow from Do because Do does not return anything:

fat[x_] := Module[{result = 1},
Table[   result *= i,   {i, 1, 2 x - 1, 2}  ] // Prepend[1]
]

• Generate a symbolic continued fraction: t = x; Do[t = 1/(1 + t), {5}]; t But this actually works! – kile Jan 2 at 13:41
• If you have to use Do then: fat[x_] := Module[{results = {1}, result = 1}, Do[result = result*i; AppendTo[results, result], {i, 1, 2 x - 1, 2}]; results] ` – Rohit Namjoshi Jan 2 at 14:11
• @kile Except that is a final fraction not each step like above. – Kuba Jan 2 at 14:12
• @rohit Iterating with AppendTo will not scale well. – Kuba Jan 2 at 14:13
• @Kuba Yes, thanks. I should have mentioned that. kile take a look at this – Rohit Namjoshi Jan 2 at 14:18