@@ -202,6 +202,48 @@ function factorial(n) {
202
202
}
203
203
</JAVASCRIPT >
204
204
</SNIPPET >
205
+ <SOLUTION >
206
+ (Solution by GitHub user escolmebartlebooth)
207
+ In <JAVASCRIPTINLINE >factorial(n)</JAVASCRIPTINLINE >, the function
208
+ <JAVASCRIPTINLINE >iter(product, counter)</JAVASCRIPTINLINE > is seeded by the
209
+ arguments <JAVASCRIPTINLINE >(1, 1)</JAVASCRIPTINLINE > and runs until
210
+ <JAVASCRIPTINLINE >counter > n</JAVASCRIPTINLINE >, at which point the product is
211
+ returned. Unlike <JVASCRIPTINLINE >gcd(a, b)</JVASCRIPTINLINE >, the register
212
+ machine has no need of a temporary register assuming that the correct order of
213
+ register assignment is followed.
214
+
215
+ For the data path, we see three registers:
216
+ <JAVASCRIPTINLINE >product</JAVASCRIPTINLINE >,
217
+ <JAVASCRIPTINLINE >counter</JAVASCRIPTINLINE >, and
218
+ <JAVASCRIPTINLINE >n</JAVASCRIPTINLINE >. There are two operations:
219
+ <JAVASCRIPTINLINE >multiply</JAVASCRIPTINLINE > and
220
+ <JAVASCRIPTINLINE >plus</JAVASCRIPTINLINE > with two assignments.
221
+ There is one test: <JAVASCRIPTINLINE >greater than</JAVASCRIPTINLINE >.
222
+
223
+ <FIGURE src =" img_javascript/ex5-1-solution-1.png" >
224
+ <LABEL NAME = " ex:5-1" />
225
+ </FIGURE >
226
+
227
+ For the controller, we start by filling the three registers with the desired
228
+ factorial <JAVASCRIPTINLINE >n</JAVASCRIPTINLINE > and the value
229
+ <JAVASCRIPTINLINE >1</JAVASCRIPTINLINE > (seeding
230
+ <JAVASCRIPTINLINE >product</JAVASCRIPTINLINE > and
231
+ <JAVASCRIPTINLINE >counter</JAVASCRIPTINLINE >). The function
232
+ <JAVASCRIPTINLINE >iter</JAVASCRIPTINLINE > runs and tests whether
233
+ <JAVASCRIPTINLINE >counter > n</JAVASCRIPTINLINE >. If
234
+ <JAVASCRIPTINLINE >counter < = n</JAVASCRIPTINLINE >, then
235
+ <JAVASCRIPTINLINE >product</JAVASCRIPTINLINE > is updated to
236
+ <JAVASCRIPTINLINE >product * counter</JAVASCRIPTINLINE >, followed by counter being
237
+ updated to
238
+ <JAVASCRIPTINLINE >counter + 1</JAVASCRIPTINLINE > and the process is repeated until
239
+ <JAVASCRIPTINLINE >counter > n</JAVASCRIPTINLINE >. Once counter is > n, the product
240
+ is
241
+ <JAVASCRIPTINLINE >factorial(n)</JAVASCRIPTINLINE > and can be returned.
242
+
243
+ <FIGURE src =" img_javascript/ex5-1-solution-2.png" >
244
+ <LABEL NAME = " ex:5-1-2" />
245
+ </FIGURE >
246
+ </SOLUTION >
205
247
</EXERCISE >
206
248
207
249
<INDEX >data paths for register machine<CLOSE /></INDEX >
0 commit comments