Yves Nkeramihigo
Yves Nkeramihigo

Reputation: 1

A LMC(little man computer) program to multiply two negative numbers

Can you help me to write a lmc program to multiply 2 negatives (-x)*(-y) = xy? For example, if you input -5 and -6, it should give you 30.

I have done for x*y=xy

INP
STA FIRST
INP
STA SECOND
LOOP LDA COUNT
ADD ONE
STA COUNT
LDA TOTAL
ADD FIRST
STA TOTAL
LDA SECOND
SUB COUNT
BRZ ENDLOOP
BRA LOOP
ENDLOOP LDA TOTAL
OUT
HLT
ONE DAT 001
COUNT DAT
TOTAL DAT
FIRST DAT
SECOND DAT

Upvotes: 0

Views: 981

Answers (1)

Maren Kjensli
Maren Kjensli

Reputation: 1

You can always just make your inputs positive before you multiply them. This of course requires the user to enter only negative numbers, or only positive numbers (it will not work with one negative and one postive input).

In the code I have added a variable ZERO which equals to 0. Then I subtract the user's input from zero and we'll be left with the positive version. Then you can use the code you have written to solve the calculation.

        INP
        BRP JUMP
        STA FIRST
        LDA ZERO
        SUB FIRST
        OUT
JUMP    STA FIRST
        INP
        BRP JUMP2
        STA SECOND
        LDA ZERO
        SUB SECOND
        OUT
JUMP2   STA SECOND
LOOP    LDA COUNT
        ADD ONE
        STA COUNT
        LDA TOTAL
        ADD FIRST
        STA TOTAL
        LDA SECOND
        SUB COUNT
        BRZ ENDLOOP
        BRA LOOP
ENDLOOP LDA TOTAL
        OUT
        HLT
ONE     DAT 001
COUNT   DAT
TOTAL   DAT
FIRST   DAT
SECOND  DAT

Upvotes: 0

Related Questions