browser

factorial8.xyw

factorial8.xyw
calendarsave
.include "lib/macros.xyw"

; Main program: calculate and print factorial of 5
$05 fact JSRw 
putd JSRw
NL
HLT

; Factorial subroutine
; a8 -[xy]-
.label fact
  ; Save argument to both registers
  POPxy
  .label fact.loop 
    PSHy $00 EQU fact.end0 JCNw
    PSHy $01 EQU fact.end1 JCNw
    ; Decrement y and multiply
    DECy PSHx PSHy MULx POPx
    fact.loop JMPw
  .label fact.end0
    ; Edge case: factorial of 0 is 1
    $01
    RTS
  .label fact.end1
    ; Return result
    PSHx
    RTS

.include "lib/putd.xyw"