-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.asm
115 lines (101 loc) · 1.67 KB
/
utils.asm
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
.text
.eqv sbrk_stack_size 4
.eqv sbrk_ra 0
sbrk:
addi $sp, $sp, -sbrk_stack_size
sw $ra, sbrk_ra($sp)
li $v0, 9
syscall
lw $ra, sbrk_ra($sp)
addi $sp, $sp, sbrk_stack_size
jr $ra
.text
.eqv fr_ra -4
.eqv fr_n 0
.eqv fr_stack_size 8
factorial_recursive:
# store
# n = $s0
addi $sp, $sp, -fr_stack_size
sw $ra, fr_ra($sp)
sw $s0, fr_n($sp)
move $s0, $a0
fr_begin_if:
bgt $s0, 1, fr_end_if # n > 1
# restore
lw $s0, fr_n($sp)
addi $sp, $sp, fr_stack_size
li $v0, 1
jr $ra
fr_end_if:
# result = n * factorial_recursive(n - 1)
addi $a0, $s0, -1 # n = n - 1
jal factorial_recursive
mul $v0, $s0, $v0
# restore
lw $s0, fr_n($sp)
lw $ra, fr_ra($sp)
addi $sp, $sp, fr_stack_size
jr $ra
.text
is_prime:
# n = a0
li $t0, 2 # i = 2
is_prime_begin_for:
bge $t0, $a0, is_prime_end_for # if i >= n
div $a0, $t0
mfhi $t1 # t1 = n % i
is_prime_begin_if:
bne $t1, 0, is_prime_end_if # t1 != 0
# if (t1 == 0) return 0
li $v0, 0
jr $ra
is_prime_end_if:
add $t0, $t0, 1 # i = i + 1
b is_prime_begin_for
is_prime_end_for:
# return 1
li $v0, 1
jr $ra
.text
factorial:
li $t0, 2 # i = 2, a0 = n
li $v0, 1 # result = 1
factorial_for_begin:
bgt $t0, $a0, factorial_for_end # i > n
mul $v0, $v0, $t0 # result = result * i
add $t0, $t0, 1
b factorial_for_begin
factorial_for_end:
jr $ra
.text
exit:
li $v0, 10
syscall
jr $ra
.text
print_string:
li $v0, 4
syscall
jr $ra
.text
print_new_line:
li $v0, 4
la $a0, __PNL_new_line
syscall
jr $ra
.text
print_int:
li $v0, 4
syscall
move $a0, $a1
li $v0, 1
syscall
jr $ra
.text
read_int:
li $v0, 5
syscall
jr $ra
.data
__PNL_new_line: .asciiz "\n"