Skip to content

Instantly share code, notes, and snippets.

@smarr
Created November 6, 2019 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smarr/b5b2c1cfbc09af64aacc51ee21912b99 to your computer and use it in GitHub Desktop.
Save smarr/b5b2c1cfbc09af64aacc51ee21912b99 to your computer and use it in GitHub Desktop.
8-bit implementation of a recursive fibonacci
; Fibonacci
; executable with https://schweigi.github.io/assembler-simulator/
; Result is in register A
JMP .start
; fib(n) <- n is in register A
fib:
CMP A, 1 ; compare n to a
JE .fibReturnOne
JB .fibReturnZero
PUSH A ; remember n on the stack
DEC A ; n - 1
CALL fib ; fib(n - 1)
MOV B, A ; remember result of fib(n - 1) in B
POP A ; take n from stack and put it in A
PUSH B ; put result of fib(n - 1) from B onto stack
SUB A, 2 ; n - 2
CALL fib ; fib(n - 2)
POP B ; put result of fib(n - 1) back into B
ADD A, B ; fib(n - 1) + fib(n - 2) (in A)
RET
.fibReturnOne:
; result is in register A
MOV A, 1
RET
.fibReturnZero:
; result is in register A
MOV A, 0
RET
.start:
MOV A, 10
CALL fib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment