Implemented factorial16.xyw.
h3rald h3rald@h3rald.com
Thu, 05 Feb 2026 16:27:32 +0100
5 files changed,
37 insertions(+),
56 deletions(-)
D
examples/factorial.xyw
@@ -1,53 +0,0 @@
-.include "devices.xyw" - -; ;ain program: calculate and print factorial of 5 -$5 fact JSRw -print8 JSRw -$0A terminal.output STB -end JMPw - -; Factorial subroutine -; a8 -- | [xy] -.label fact - ; Save argument to both registers - POPxy - .label fact.loop - PSHy $0 EQU fact.end0 JCNw - PSHy $1 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 - $1 - CLRxy - RTS - .label fact.end1 - ; Return result - PSHx - CLRxy - RTS - -; Printing subroutine -; a8 -- | [xy] -.label print8 - POPx - ; If value is less than 10, print single digit - PSHx $A LTH print8.single JCNw - ; Divide by 10: stack becomes [remainder, quotient] - PSHx $A DIV - ; Save remainder to y for later - SWP POPy - ; Call print8 recursively with quotient (still on stack) - print8 JSRw - ; Print the saved remainder - PSHy $30 ADD terminal.output STB - CLRxy - RTS - .label print8.single - ; Print single digit - PSHx $30 ADD terminal.output STB - CLRx - RTS - -.label end
A
examples/factorial16.xyw
@@ -0,0 +1,35 @@
+.include "devices.xyw" + +; Main program: calculate and print factorial of 7 +$00 $07 fact JSRw +print16 JSRw +$0A terminal.output STB +end JMPw + +; 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 $00 $00 EQUw SWP POP fact.end0 JCNw + PSHyw $00 $01 EQUw SWP POP 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 + $1 + CLRxyw + RTS + .label fact.end1 + ; Return result + PSHxw + CLRxyw + RTS + +.include "print16.xyw" + +.label end
M
examples/factorial8.xyw
→
examples/factorial8.xyw
@@ -1,6 +1,6 @@
.include "devices.xyw" -; ;ain program: calculate and print factorial of 5 +; Main program: calculate and print factorial of 5 $5 fact JSRw print8 JSRw $0A terminal.output STB
M
examples/print16.xyw
→
examples/print16.xyw
@@ -20,5 +20,3 @@ ; Print single digit (need low byte of XW since value is 0-9)
PSHxw SWP POP $30 ADD terminal.output STB CLRxw RTS - -.label end
M
test.sh
→
test.sh
@@ -8,6 +8,7 @@ "run_test d6.xyw assert_output_in_range 1 6"
"run_test on-error.xyw assert_output_equals \$'Error: Division by zero.\\nError: Unknown error.\\n'" "run_test print-args.xyw test1 test2 -- assert_output_equals \$'print-args.xim, test1, test2\\n'" "run_test factorial8.xyw assert_output_equals \$'120\\n'" + "run_test factorial16.xyw assert_output_equals \$'5040\\n'" ) ### Helper functions