Created
March 24, 2022 08:48
-
-
Save aflaag/d1fccee539376ad3a8e6c82601f67a4e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| .globl main | |
| .data | |
| N: .word 5 | |
| .text | |
| main: | |
| lw $a0, N($zero) # a0 = N[0] | |
| move $v0, $zero # v0 = 0 | |
| jal factorial # v0 = factorial(a0) | |
| move $a0, $v0 # a0 = v0 | |
| li $v0, 1 # print int | |
| syscall | |
| li $v0, 10 # exit | |
| syscall | |
| # Returns the factorial of | |
| # the given number in $a0. | |
| # fn factorial(a0: int) -> (v0: int) | |
| # return a0 * factorial(a0 - 1) | |
| factorial: | |
| beqz $a0, base_case # go to base_case if a0 == 0 | |
| recursive_case: | |
| subi $sp, $sp, 8 # sp -= 8 | |
| sw $a0, 4($sp) # mem[sp + 4] = a0 | |
| sw $ra, 0($sp) # mem[sp + 0] = ra | |
| sub $a0, $a0, 1 # a0 -= 1 | |
| jal factorial # factorial(a0) | |
| lw $ra, 0($sp) # ra = mem[sp + 0] | |
| lw $a0, 4($sp) # a0 = mem[sp + 4] | |
| addi $sp, $sp, 8 # sp += 8 | |
| mul $v0, $v0, $a0 # v0 *= a0 | |
| jr $ra | |
| base_case: | |
| li $v0, 1 # v0 = 1 | |
| jr $ra |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment