diff --git a/static/img_javascript/ex5-1-solution-1.png b/static/img_javascript/ex5-1-solution-1.png new file mode 100644 index 000000000..8edb00e56 Binary files /dev/null and b/static/img_javascript/ex5-1-solution-1.png differ diff --git a/static/img_javascript/ex5-1-solution-2.png b/static/img_javascript/ex5-1-solution-2.png new file mode 100644 index 000000000..853c686fe Binary files /dev/null and b/static/img_javascript/ex5-1-solution-2.png differ diff --git a/xml/chapter5/section1/section1.xml b/xml/chapter5/section1/section1.xml index b95014ced..8c8ccc390 100644 --- a/xml/chapter5/section1/section1.xml +++ b/xml/chapter5/section1/section1.xml @@ -202,6 +202,48 @@ function factorial(n) { } + + (Solution by GitHub user escolmebartlebooth) + In factorial(n), the function + iter(product, counter) is seeded by the + arguments (1, 1) and runs until + counter > n, at which point the product is + returned. Unlike gcd(a, b), the register + machine has no need of a temporary register assuming that the correct order of + register assignment is followed. + + For the data path, we see three registers: + product, + counter, and + n. There are two operations: + multiply and + plus with two assignments. + There is one test: greater than. + +
+
+ + For the controller, we start by filling the three registers with the desired + factorial n and the value + 1 (seeding + product and + counter). The function + iter runs and tests whether + counter > n. If + counter <= n, then + product is updated to + product * counter, followed by counter being + updated to + counter + 1 and the process is repeated until + counter > n. Once counter is > n, the product + is + factorial(n) and can be returned. + +
+
+
data paths for register machine