factorial16.xyw
factorial16.xyw.include "lib/macros.xyw"
; Main program: calculate and print factorial of 7
$0007 fact JSRw
putdw JSRw
NL
HLT
; Factorial subroutine
; a16 -[xy]-
.label fact
; Save argument to both registers
POPxyw
.label fact.loop
; Need to work with 16-bit comparisons
; but JCN only works with 8-bit values, so remove high byte first
PSHyw $0000 EQUw LBYTE fact.end0 JCNw
PSHyw $0001 EQUw LBYTE fact.end1 JCNw
; Decrement y and multiply
DECyw PSHxw PSHyw MULxw POPxw
fact.loop JMPw
.label fact.end0
; Edge case: factorial of 0 is 1
$0001
RTS
.label fact.end1
; Return result
PSHxw
RTS
.include "lib/putdw.xyw"