forked from 61c-teach/su21-lab-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factorial.s
57 lines (42 loc) · 1.17 KB
/
factorial.s
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
52
53
54
55
56
57
.globl factorial
.data
n: .word 8
.text
main:
la t0, n
lw a0, 0(t0)
jal ra, factorial
addi a1, a0, 0
addi a0, x0, 1
ecall # Print Result
addi a1, x0, '\n'
addi a0, x0, 11
ecall # Print newline
j write_tohost
factorial:
addi sp, sp, -4 # Allocate space on the stack
sw ra, 0(sp) # Save return address on the stack
beqz a0, base_case # Base case: if n == 0, return 1
addi sp, sp, -4 # Allocate space on the stack
sw a0, 0(sp) # Save n on the stack
addi a0, a0, -1 # Decrement n
jal ra, factorial # Recursively call factorial with n-1
lw a1, 0(sp) # Load n from the stack
addi sp, sp, 4 # Deallocate space on the stack
mul a0, a1, a0 # Multiply n by the result of the recursive call
j end_factorial
base_case:
addi a0, x0, 1 # Base case: return 1
end_factorial:
lw ra, 0(sp) # Load return address from the stack
addi sp, sp, 4 # Deallocate space on the stack
jr ra # Return
write_tohost:
li x1, 1
sw x1, tohost, t5
j write_tohost
.data
.align 12
.section ".tohost","aw",@progbits
.align 4; .global tohost; tohost: .dword 0
.align 4; .global fromhost; fromhost: .dword 0