Providing an LMC with negative input is not supported by the specification. LMC memory cells can only hold values between 0 and 999 (source: Wikipedia). The only notion of "negative" is represented by the LMC's negative flag. And that flag is only set by the execution of ADD
or SUB
, so not by INP
/IN
, LDA
or STA
/STO
(spellings differ). See also these notes of Ian! D. Allen where he discusses this confusing concept.
This practically means that your BRP
instruction will always branch to the provided label.
You may find simulators that actually allow negative input, but that would be an extension to the original specifications.
Now, your code also has an issue with this BRP POS
instruction, because it just jumps to the next line (labeled POS
), so it actually would not make any difference whether BRP
would branch or not: it is a no-operation.
A similar exercise
As negative values do not really exist in LMC, let's do the exercise a bit differently: consider the input as presented in 10's-complement, so that 500..999 are to be considered negative values (i.e. -500...-1). Or, that signed input values will actually get stored in 10's-complement when you do INP
. Then count the number of inputs that are less than 500 (positive) and those that are not (as these are negative when interpreted as 10's-complement).
LOOP INP
BRZ FINISH
SUB COMPARE
BRP ELSE
LDA LESS
ADD ONE
STA LESS
BRA LOOP
ELSE LDA NOTLESS
ADD ONE
STA NOTLESS
BRA LOOP
FINISH LDA LESS
OUT
LDA NOTLESS
OUT
HLT
LESS DAT
NOTLESS DAT
COMPARE DAT 500
ONE DAT 1
<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.6/lmc.js"></script>
Be sure to supply a final 0 value for the program to output the result.