spo/ass1/rec.asm
2025-11-12 09:01:11 +01:00

136 lines
No EOL
2 KiB
NASM

rec START 0
JSUB stackinit
mainloop JSUB readnum
COMP #0 .if 0 halt
JEQ halt
JSUB fac
JSUB printnum
J mainloop
readnum STL readret
LDA #0
STA currentnum
readchar RD devFA
COMP #10 .stop reading if newline
JEQ endread
COMP #48 .stop reading if 0
JEQ endread
SUB #48
STA temp
LDA currentnum
MUL #10
ADD temp
STA currentnum
J readchar
endread LDA currentnum
LDL readret
RSUB
ending LDA temp
JSUB printnum
J mainloop
printnum STL printret
STA num
LDA #0
STA digitcnt
divloop LDA num
COMP #0
JEQ checkzero
DIV #10
STA quotient
MUL #10
STA saveA
LDA num
SUB saveA
ADD #48 .convert to ascii number
STA @stkptr
JSUB push
LDA digitcnt
ADD #1
STA digitcnt
LDA quotient
STA num
J divloop
checkzero LDA digitcnt
COMP #0
JGT printloop
LDA #48
WD devAA
LDL printret
RSUB
printloop LDA digitcnt
COMP #0
JEQ printdone
LDB stkptr
COMPR X, B .stop print if stack empty
JEQ printdone
JSUB pop
WD devAA
LDA digitcnt
SUB #1
STA digitcnt
J printloop
printdone LDL printret
LDA #0x0A .print newline
WD devAA
RSUB
halt J halt
fac COMP #1 .base case
JGT facrecur
LDA #1
RSUB
.only works for < 10 (24 bit registers)
facrecur JSUB push .recursive case
SUB #1
JSUB fac
STA temp
STL lastJ .save jump register
LDB stkptr
COMPR X, B .exit if stack empty
JEQ ending
JSUB pop
MUL temp
LDL lastJ
RSUB
push STA temp
STA @stkptr
LDA stkptr
ADD #3
STA stkptr
LDA temp
RSUB
pop STA temp
LDA stkptr
SUB #3
STA stkptr
LDA @stkptr
RSUB
stackinit STA temp
LDA #stack
STA stkptr
LDX stkptr
LDA temp
RSUB
stkptr RESW 1
temp RESW 1
lastJ RESW 1
printret RESW 1
readret RESW 1
currentnum RESW 1
num RESW 1
quotient RESW 1
saveA RESW 1
digitcnt RESW 1
stack RESW 50
devFA BYTE X'FA'
devAA BYTE X'AA'
END rec