mod(x,y) works for unsigned integers, but not for signed integers in nand2tetris. What changes should I make?

99 views Asked by At
    @R2
    M=0
    @R0
    D=M
    @END
    D, JEQ
    @store
    M=D 
(LOOP)
    @R1
    D=D-M
    @REMAINDER
    D, JLT
    @EVENLY
    D, JEQ
    @LOOP
    0, JMP
(REMAINDER)
    @R1
    D=D+M
    @R2
    M=D
(EVENLY)
    @store
    D=M
    @R0
    M=D
(END)
    @END
    0, JMP
1

There are 1 answers

0
MadOverlord On

You should identify the conditions under which your current code works, and fails. Does it require both operands to be positive, or just have the same sign?

Once you have done that, you also know the conditions under which it fails. You can then check for those, and either execute different code under those conditions, or modify the operands so that the current code works and generates the proper result.

To get you started, here's some examples of what modulo should return. Good luck!

Python 3.8.1 (default, Jan 15 2020, 18:56:16) 
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 3 % 2
1
>>> 3 % -2
-1
>>> -3 % -2
-1
>>> -3 % 2
1
>>> 5 % 3
2
>>> 5 % -3
-1
>>> -5 % 3
1
>>> -5 % -3
-2