yeolyi.comSeongyeol's CS

Swapping Programs

The computer in The Finished Computer has a multiplication program in memory, so all it does is multiply. To make it do something else, we don’t need to touch the circuit. Let’s just put a different program into memory.

Odd or even

First, let’s find out whether the number in slot 13 is odd or even. There is no division instruction, so we repeat subtracting 1 twice. If the first subtraction reaches 0, the number is odd, so we write 1 to slot 15; if the second one reaches 0, it’s even, so we write 0.

0LOAD 13
1SUBI R0, 1
2JZ 6
3SUBI R0, 1
4JZ 7
5JUMP 1
6LDI R0, 1
7STORE 15
8HALT
90
100
110
120
137
140
150
R00
Z0

Runs from address 0.

Press play to run it. The 7 in slot 13 is odd, so 1 is written to slot 15.

Fibonacci numbers

Now let’s put another program into memory. A sequence like 1, 1, 2, 3, 5, 8, where each number is the sum of the two before it, is called the Fibonacci numbers. We keep two neighboring numbers in R1 and R2, write the first one to slot 15, and shift both along by one. We repeat this as many times as the number in slot 13.

0LOAD 13
1MOVE R3, R0
2LDI R1, 1
3LDI R2, 1
4MOVE R0, R1
5STORE 15
6ADD R0, R2
7MOVE R1, R2
8MOVE R2, R0
9SUBI R3, 1
10JZ 12
11JUMP 4
12HALT
138
140
150
R00
R10
R20
R30
Z0

Runs from address 0.

Press play and watch slot 15. 1, 1, 2, 3, 5, 8, 13, 21 are written in turn.

Wrapping up

It’s one machine, but depending on the numbers in memory, it becomes an odd-or-even checker or a sequence calculator. But to put these programs into memory, we have to turn each instruction like LOAD 13 into binary like 10001101 by hand. In the next post, let’s hand that job to a program.

Challenge

In the post's Fibonacci demo, if we change the 8 in slot 13 to 14, what is the 14th number written to slot 15? Answer with a number.