Skip to content

Instantly share code, notes, and snippets.

@nathggns
Last active January 26, 2017 12:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathggns/9757c105138c74f39dd4 to your computer and use it in GitHub Desktop.
Save nathggns/9757c105138c74f39dd4 to your computer and use it in GitHub Desktop.
Fibonacci Generator in LMC

LMC Fibonacci Generator

Screenshot

You can run this program on any LMC emulator, such as http://peterhigginson.co.uk/LMC/

LMC, which stands for Little Man Computer is a model of a computer, used to teach students how CPUs work. Read More.

Lines 1-2

  • Takes a number as an input, and stores it in a mailbox labelled N. We will not attempt to find any number in the sequence larger than this number.

Lines 3-5

  • We start the loop process by loading in the value from mailbox A. We've labelled this mailbox LOOP as this is the start of the loop for generator the sequence.
  • We then enter in to the logic for deciding if we have reached our limit to the sequence. In a language with complex conditionals, we would use something like if a > n, but LMC doesn't have that. Instead, we reverse it so we do if a - n > 0, which we can do in LMC using BRP.
  • We have loaded A into the accumulator at the start of the loop, and so we simply need to take away our sequence maximum, N. We do this on line 4.
  • We know that if the accumulator is a negative number, then we have reached the end of the sequence that we want to generate and so we can skip to the end of the program, which we have labelled as ENDLOOP. We do this with BRP, which will branch to a mailbox if the accumulator value is a negative number.

Lines 6-7

  • This is simply loading A back into the accumulator and outputting it, so we can see each item in the sequence.

Lines 8-14

  • This is the logic for how we generate a fibonacci sequence. It's the equivalent to something like a, b = b, a + b. Unfortunately, we need the mailbox ACC as I'm not sure that there is an easy way to swap the values in mailboxes in LMC.

Line 15

  • This jumps back to the start of the loop, where we'll check if the sequence is done.

Line 16

  • This is the end of the program, labelled ENDLOOP so we can end the loop once the sequence is done.

Line 17-20

  • This is just labelling a few memory boxes.

Issues

  • We're using a swap memory box, ACC, which we may or may not need. It should probably be called SWP anyway.
  • The sequence starts on 0, whereas a real fibonacci sequence starts on 1.
INP
STA N
LOOP LDA A
SUB N
BRP ENDLOOP
LDA A
OUT
LDA B
ADD A
STA ACC
LDA B
STA A
LDA ACC
STA B
BRA LOOP
ENDLOOP HLT
A DAT 0
B DAT 1
N DAT
ACC DAT
@onstanleyon
Copy link

Brilliant

@marabb01
Copy link

My entire class benefited from this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment