little-man-computer

How to check if a number is odd or even in little man computer


I need help with making my program produce the correct output.

I am currently working with this code:

        INP
        STA NUMBER
        SUB DIVISOR
        BRP VERIFY
        BRA CHECK
LOOP    STA NUMBER
        LDA RESULT
        ADD ONE
        STA RESULT
VERIFY  LDA NUMBER
        SUB DIVISOR
        BRP LOOP
        LDA RESULT
ODD     LDA ONE
        STA RESULT
EVEN    LDA 60
        STA RESULT 
CHECK   LDA RESULT
        BRP ODD
        BRZ EVEN
        OUT
        HLT
NUMBER  DAT
DIVISOR DAT 2
ONE     DAT 1
RESULT  DAT 0

When I run the code above on little man computer simulator, it just loops and loops and prints no output. What I wanted to do is divide the inputted number into two and check if it has a remainder. If it has a remainder, then it is an odd number, else it is an even number. I know that the code has errors but I can't pinpoint where the problem lies, maybe you can help me with it. Thanks in advance!


Solution

  • The infinite loop occurs at BRP ODD. Be aware that BRP also branches when the accumulator is zero. So it is a "branch when not negative" instruction. And when the execution continues at ODD, it falls through to EVEN, which makes the code at ODD irrelevant. At EVEN the accumulator is loaded with zero, and so the BRP will branch again... infinitely.

    There is also a missing check for 0: when the input is zero, you should not perform the subtraction at all.

    Not a problem, but having a reference to mailbox 60 can be better replaced with a reference to a label, like ZERO.

    The code includes logic that really isn't necessary:

    You have included code to calculate the quotient, since the code adds ONE to the RESULT every time you subtract the DIVISOR from the NUMBER. However, that RESULT is finally overwritten with either ONE or zero (address 60), so that quotient was calculated for nothing. As you only want to output whether the input was odd or even, you should drop the quotient calculation from your code.

    Also avoid code repetition. You currently perform the SUB at two different places. This should not be necessary as the logic should be the same in both instances.

    Here is the code reduced to its basics:

    #input: 11
            INP
            STA NUMBER
    LOOP    BRZ OUTPUT  # remainder is zero! so output a zero
            SUB DIVISOR
            BRP LOOP
            LDA ONE   # when result is negative, input was odd
    OUTPUT  OUT
            HLT
    NUMBER  DAT
    DIVISOR DAT 2
    ONE     DAT 1
    ZERO    DAT 0
    
    
    <script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.816/lmc.js"></script>

    You can run the simulator in this snippet and then use the buttons to step through the code.