I need to write an LMC program to calculate the value of a+bx+cx² for given values of a, b, c and x. If the result exceeds 999, then it needs to output 999; if less than 999, then output the result.
The a+bx+x² part (without c-coefficient) is already done by @trincot in this answer:
INP
STA a
INP
STA b
INP
STA x
STA x2
LDA z # "inverse" ans
SUB a # do this first
loop STA ans
LDA x
BRZ output
SUB one
STA x
LDA ans
SUB x2 # subtract both x...
BRP continue
BRA overflow
continue SUB b # ... and b
BRP loop
overflow LDA zero # prepare for outputing 999 (overflow)
STA ans
output LDA z
SUB ans # 999 - (999 - (a + bx + x^2))
OUT
HLT
a DAT 0
b DAT 0
x DAT 0
x2 DAT 0
z DAT 999
ans DAT 0
zero DAT 0
one DAT 1
But have no idea how to modify this code so to add c times x²
To minmise on the logic you need, you could calculate − − ² as follows:
− ( − )
This has a recursive pattern, so that the logic to use for the inner expression − is the same as the logic for the outer expression once you have the result for the inner one: − . If we swap values in the variables , and , we can execute this sequence:
:= −
:=
:= −
...and then will be the final answer. Clearly we can put the following in a loop that is executed twice:
:= −
:=
The second thing to consider is what the code already does. I quote from my answer from where that code originates:
So here we would perform that "inversion" at the start of the loop, then keep subtracting (instead of adding) and finally (if no negative overflow occurred) invert the result again.
Here is an implementation of that idea -- you can run it here: