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 › Digits

Halve before you square; check the box first

Say you're drawing a picture 120 wide and want to know whether a point is within 20 of the middle. Its distance dx can be anything up to 60.

The textbook way squares dx and compares it with 20 squared. But here's the problem: a cell only keeps three digits, and 60 squared is 3600. Try dx = 33. Its square is 1089, the cell keeps 089, and the program cheerfully tells you the point is inside.

cell  contents  notes
 10      040    INP 40  cell 10: dx, up to 60 from the middle
 11      144    CLA 44  cells 11-27: dx squared: add dx to itself dx times, counting up from -dx
 12      740    SUB 40
 13      641    STO 41
 14      142    CLA 42
 15      240    ADD 40
 16      642    STO 42
 17      141    CLA 41
 18      200    ADD 00
 19      641    STO 41
 20      314    TAC 14
 21      142    CLA 42  inside when dx squared is below r squared, 400
 22      743    SUB 43
 23      326    TAC 26
 24      544    OUT 44
 25      900    HRS 00
 26      500    OUT 00  inside: print 1
 27      900    HRS 00
 40      000
 41      000
 42      000    dx squared, kept in a cell: only its last three digits
 43      400
 44      000

Step through the natural way in Cardigan

So check the box first. If dx isn't below 20, the point is outside and there's nothing to square at all. Inside the box, dx is under 20, and its square fits in a cell just fine. If you really do need squares across the whole range, halve first: 30 squared is 900, which fits.

cell  contents  notes
 10      040    INP 40  cells 10-15: first the box: dx not below r means outside, with no square at all
 11      140    CLA 40
 12      743    SUB 43
 13      316    TAC 16
 14      545    OUT 45
 15      900    HRS 00
 16      145    CLA 45  cells 16-32: dx squared: add dx to itself dx times, counting up from -dx
 17      740    SUB 40
 18      641    STO 41
 19      142    CLA 42
 20      240    ADD 40
 21      642    STO 42
 22      141    CLA 41
 23      200    ADD 00
 24      641    STO 41
 25      319    TAC 19
 26      142    CLA 42  inside the box, dx is below 20, and its square fits
 27      744    SUB 44
 28      331    TAC 31
 29      545    OUT 45
 30      900    HRS 00
 31      500    OUT 00  inside: print 1
 32      900    HRS 00
 40      000
 41      000
 42      000
 43      020
 44      400
 45      000

Step through the CARDIAC way in Cardigan

The first version prints 1, which is wrong, after 240 instructions. The second prints 0, which is right, after 6. It does take more cells, 29 against 23, because it has the box check as well as the square.

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