CARDIAC › Tips and tricks › Digits
Tell odd from even with 5n
Say you want to know whether n is odd.
CARDIAC can't divide, so the remainder after dividing by 2 means walking: take 2 away until n goes negative, and look at what's left. Even walking in the accumulator, as in "Subtract until it goes negative, then add one back", that's three instructions for every 2 in n, and 123 takes 62 subtractions.
cell contents notes
10 040 INP 40 cells 10-14: take 2 away from n until it goes negative
11 140 CLA 40
12 741 SUB 41
13 315 TAC 15
14 812 JMP 12
15 200 ADD 00 cells 15-20: -1 is left when n is odd, -2 when it is even
16 319 TAC 19
17 500 OUT 00 odd: print 1
18 900 HRS 00
19 542 OUT 42 even: print 0
20 900 HRS 00
40 000 n
41 002
42 000
Step through the natural way in Cardigan
Multiply by 5 instead. 5n ends in 0 when n is even and in 5 when n is odd, so every even number looks the same, and so does every odd one. Times 5 is four additions, and SFT 33 keeps only the last digit. Take away the 1 in cell 00, and 0 goes negative while 5 doesn't. The accumulator holds four digits, so 5n fits for any n up to 999. There's a bonus, too: the same 5n with SFT 01 is half of n, rounded down, so a program that halves n and tests it for odd does both with one multiply.
cell contents notes
10 040 INP 40 cells 10-16: 5n ends in 5 when n is odd and in 0 when it is even; SFT 33 keeps that digit
11 140 CLA 40
12 240 ADD 40
13 240 ADD 40
14 240 ADD 40
15 240 ADD 40
16 433 SFT 33
17 700 SUB 00 cells 17-22: 0 - 1 is negative, 5 - 1 isn't
18 321 TAC 21
19 500 OUT 00 odd: print 1
20 900 HRS 00
21 541 OUT 41 even: print 0
22 900 HRS 00
40 000 n
41 000
Step through the CARDIAC way in Cardigan
Both say 123 is odd. Walking takes 14 cells and runs 191 instructions; 5n takes 15 cells and runs 11, the same 11 for every n.
On a binary machine the odd test is cheaper still, because evenness lives in the lowest bit. Testing n & 1 tells you, a shift right by one halves n, and compilers turn n % 2 and n / 2 into those for you, with a small correction when n might be negative. Swapping an expensive operation for a cheap one like this is called strength reduction. 5n is the decimal version of the same idea. Since 10 is 2 times 5, multiplying by 5 moves the halving and the oddness into whole digits, where SFT can reach them.
From the tips in
cardiac-code on GitHub. All the tips.