0

I've managed to code an LMC program which works on this simulator for performing integer division. However if there is a remainder it goes into an infinite loop.

I'm trying to think of a way to just keep the quotient regardless of whether there is a remainder, but I'm stuck.

One idea was to increase the dividend by the original divisor and then check for a negative value for DIVISOR before branching. However, there is only "Branch if Zero" or "Branch if positive" available, so I would probably have to re-write the program from scratch to use the inverted logic.

Can anyone please provide a version which can handle non-exact division?

// CANT HANDLE NOT-EXACT DIVISION
INP DIVIDEND
STA DIVIDEND
INP DIVISOR
STA DIVISOR
LOOP   LDA DIVIDEND
BRZ END
SUB DIVISOR
STA DIVIDEND
LDA QUOTIENT
ADD ONE
STA QUOTIENT
BRA LOOP
END   LDA QUOTIENT
OUT
SUB QUOTIENT
STA QUOTIENT
HLT
DIVIDEND    DAT
DIVISOR    DAT
QUOTIENT    DAT 0
ONE   DAT 1
Robin Andrews
  • 3,514
  • 11
  • 43
  • 111

1 Answers1

1

There are several solutions. You could for instance use BRP to continue from the top of the loop, but than also move some of the logic to the start of the loop, which you must skip upon entering the loop the first time.

Some other remarks: protect your code from division by zero (infinity looping). On the other hand it is not needed to test that the dividend is zero. In that case the subtraction of the divisor will anyway cause a break of the loop.

#input: 11 3
         INP 
         STA DIVIDEND
         INP 
         BRZ QUIT  // no division by zero
         STA DIVISOR
         BRA ENTRY
    LOOP STA DIVIDEND
         LDA QUOTIENT
         ADD ONE
         STA QUOTIENT
   ENTRY LDA DIVIDEND
         SUB DIVISOR
         BRP LOOP
         LDA QUOTIENT
         OUT
    QUIT HLT
DIVIDEND DAT
 DIVISOR DAT
QUOTIENT DAT 0
     ONE DAT 1

<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.7/lmc.js"></script>
trincot
  • 317,000
  • 35
  • 244
  • 286