SQ in silver chrome letters, a lab's gear stacked against the S: a rack, two oscilloscopes, pizza boxes and a six-pack. Strange Query Lab

CARDIAC › Tips and tricks › Comparisons

Subtract until it goes negative, then add one back

Say you want the remainder when x is divided by d, like 100 mod 7.

In most languages you'd write a loop: while x is at least d, take d away from x. Written that way on CARDIAC, each pass loads x, subtracts d, tests, stores x back and jumps round. That's five instructions to take away one d.

cell  contents  notes
 10      040    INP 40  cells 10-18: take d away from x and store it, while what is left isn't negative
 11      041    INP 41
 12      140    CLA 40
 13      741    SUB 41
 14      317    TAC 17
 15      640    STO 40
 16      812    JMP 12
 17      540    OUT 40
 18      900    HRS 00
 40      000    x, and then the remainder
 41      000    d

Step through the natural way in Cardigan

But there's no need to store x until you're done. Keep it in the accumulator and subtract d until it goes negative, which is one subtraction too many, then add one d back, and what's left is the remainder. That's three instructions a pass. The same loop answers "does d divide x?" and is the heart of the greatest common divisor. If you want the quotient too, you have to count the passes, and the count brings the stores back, as in "Divide by walking".

cell  contents  notes
 10      040    INP 40  cells 10-19: subtract d in the accumulator until it goes negative, then add one d back
 11      041    INP 41
 12      140    CLA 40
 13      741    SUB 41
 14      316    TAC 16
 15      813    JMP 13
 16      241    ADD 41
 17      640    STO 40
 18      540    OUT 40
 19      900    HRS 00
 40      000    x, and then the remainder
 41      000    d

Step through the CARDIAC way in Cardigan

Both print 2. Storing as you go takes 11 cells and runs 77 instructions. Staying in the accumulator takes 12 cells, one more for adding d back, and runs 51.

Textbook hardware dividers work the same way, and the method is called restoring division. Each step subtracts the divisor, and when the result goes negative, the divider adds it back and writes a 0 into the quotient. Non- restoring division was worked out to skip the adding back.

From the tips in cardiac-code on GitHub. All the tips.