# Recursion

## Recursive expressions

### Factorial

• Factorial(n) =
• 1, if n = 0
• n * Factorial(n-1), if n > 0

### Fibonacci

• Fibonacci(n) =
• 1, if n ≤ 1
• Fibonacci(n-1) + Fibonacci(n-2), if n > 1

### Euclid GCD (one variety)

• GCD(n, m) =
• GCD(m, n), if n < m
• n, if n = m
• GCD(n - m, m), if n > m

use offset
saved R2 -2
saved R1 -1
saved R0 0
dynamic link 1
return address 2
return value 3
N 4
M 5

## Code

### GCD

```        .ORIG        x4B00
;; Activation record for GCD
;;
;;  offsets to R5 during call
;;  -2 -- SAVED R2 (last local)     -- R6 here during call
;;  -1 -- SAVED R1
;;   0 -- SAVED R0 (first local)    -- R5 here during call
;;   1 -- dynamic link
;;   2 -- return PC
;;   3 -- return value  (GDC(N,M))  -- R6 here on exit
;;   4 -- ARG 1         (N)         -- R6 here on entry
;;   5 -- ARG 2         (M)
;;

;; CREATE THE ACTIVATION RECORD
GCD     STR     R7,R6,#-2      ;; Store caller PC
STR     R5,R6,#-3      ;; Store caller dynamic link
ADD     R5,R6,#-4      ;; Set R5 to first local
ADD     R6,R5,#-2      ;; Set R6 to last local

;; SAVE REGS
STR     R0,R5,#0
STR     R1,R5,#-1
STR     R1,R5,#-2

;; DO THE WORK
LDR     R0,R5,#4        ; R0 <- N
LDR     R1,R5,#5        ; R1 <- M
NOT     R2,R1
ADD     R2,R2,#1
ADD     R2,R0,R2        ; R2 <- N-M
BRz     Leave
BRp     Recurse
;; N < M -- swap
ADD     R2,R1,#0
ADD     R1,R0,#0
Recurse
STR     R0,R6,#-2        ; Push N and M on stack
STR     R1,R6,#-1
ADD     R6,R6,#-2
JSR     GCD
LDR     R0,R6,#0        ; R0 <- return value
ADD     R6,R6,#3        ; pop return value and args

Leave
;; SAVE RETURN VALUE
STR     R0,R5,#3       ;; Save return value

;; RESTORE REGS
LDR     R0,R5,#0
LDR     R1,R5,#-1
LDR     R1,R5,#-2

;; RETURN AND DELETE ACTIVATION RECORD
LDR     R7,R5,#2
ADD     R6,R5,#3
LDR     R5,R5,#1
RET

.END
```