aboutsummaryrefslogtreecommitdiff
path: root/examples/factorial.asm
blob: 42c0785ad51f9efba89dd535187542b3ea2ef6b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
;;; factorial.asm: A program that generates the factorials of each
;;;  number from 1 to 22 (22!~=UINT64_MAX).  Using the registers to
;;;  store `n` and `n!`.

  ;; Constants
  %const(limit) 22 %end

  ;; Setup entrypoint
  global main
main:
  ;; $I -> W[0] = 1, $J -> W[1] = 1
  push.word 1
  mov.word 0
  push.word 1
  mov.word 1

  ;; Print `$I: $J`
loopback:
  push.byte '\t'
  print.char
  push.reg.word 0
  print.word
  push.byte ':'
  print.char
  push.byte ' '
  print.char
  push.reg.word 1
  print.word
  push.byte '\n'
  print.char

  ;;  $I += 1
  push.reg.word 0
  push.word 1
  plus.word
  mov.word 0

  ;;  $J *= $I
  push.reg.word 0
  push.reg.word 1
  mult.word
  mov.word 1

  ;; IF $I >= $LIMIT ...
  push.word $limit
  push.reg.word 0
  gte.word
  ;; THEN jump to `loopback`
  jump.if.byte loopback
  ;; ELSE halt
  halt