Last active
November 23, 2019 17:22
-
-
Save marcuslx/db3e02ab90ac459093cd133d98d505e6 to your computer and use it in GitHub Desktop.
Recursive Factorial of an integer in MIPS assembly
This file contains 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
.data | |
n: .word 5 | |
result: .asciiz "Fact(x) = " | |
.text | |
.globl main | |
main: | |
lw $a0, n #$a0 = n | |
jal verifier | |
#print the result | |
li $v0, 4 | |
la $a0, result #prints the string: "Fact(x) = " | |
syscall | |
li $v0, 1 | |
mflo $a0 #$a0 = $lo = result of the factorial | |
syscall | |
#return 0 | |
li $v0, 10 | |
syscall | |
verifier: | |
slti $t0, $a0, 1 #if($a0<1), then $t0=1 | |
beq $t0, $zero, factorial #if($a0 >= 1) goto factorial | |
addi $v0, $zero, 1 #$v0 = 1 | |
jr $ra | |
factorial: | |
addi $sp, $sp, -8 #allocate space on stack | |
sw $ra, 0($sp) | |
sw $s0, 4($sp) | |
add $s0, $a0, $zero #$s0 = $a0 = n | |
addi $a0, $a0, -1 #$a0-- | |
jal verifier # $v0 = factorial(n-1) | |
mult $s0, $v0 #$lo = n*factorial(n-1) | |
mflo $v0 #$v0 = $lo | |
lw $s0, 4($sp) | |
lw $ra, 0($sp) | |
addi $sp, $sp, 8 #deallocate space on stack | |
jr $ra |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment