# To test this file you could use your own implementation of the machine # or mine. If you want to use mine, then here is a script: # > java duckMachine.Text # DM>> load fact.dm # DM>> run # 5 # 120 # DM>> quit # # Assembly program to read one number, compute its factorial, and print result # Corresponding Java program: # int factorial (int i) { # int result = 1; # while (i > 0) { # result = result * i; # i--; # } # return result; # } # Our assembly language does not have multiplication; let's rewrite # the program without multiplication: # int factorial (int i) { # int result = 1; # while (i > 0) { # # // The following 8 lines replace the line: result = result * i; # int left_multiply = result; # int right_multiply = i; # int multiply_result = 0; # while (right_multiply > 0) { # multiply_result += left_multiply; # right_multiply--; # } # result = multiply_result; # # i--; # } # return result; # } # Now write the thing in assembly: # result => Memory location 50 # i => Memory location 49 # left_multiply => Memory location 48 # right_multiply => Memory location 47 # multiply_result => Memory location 46 # 0 => Memory location 45 0 in 49 # read i 1 clear 50 # result = 0 2 increment 50 # result = 1 3 clear 45 # constant 0 used for various operations 4 load 45 # beginning of while (i > 0) loop 5 compare 49 # compare i and 0 6 jumpgt 9 # if (i > 0) goto 9 else goto 7 7 out 50 # print result 8 halt # DONE 9 load 50 # get result 10 store 48 # left_multiply = result 11 load 49 # get i 12 store 47 # right_multiply = i 13 clear 46 # multiply_result = 0 14 load 45 # beginning of while (right_multiply > 0) loop 15 compare 47 # compare right_multiply and 0 16 jumpgt 21 # if (right_multiply > 0) goto 21 else goto 17 17 load 46 # get multiply_result 18 store 50 # result = multiply_result 19 decrement 49 # i-- 20 jump 4 # end of while (i > 0) loop 21 load 46 # get multiply_result 22 add 48 # add to left_multiply 23 store 46 # multiply_result = multiply_result + left_multiply 24 decrement 47 # right_multiply-- 25 jump 14 # end of while (right_multiply > 0) loop