Skip to content

Instantly share code, notes, and snippets.

@bl0ckeduser
Created February 15, 2014 17:54
Show Gist options
  • Save bl0ckeduser/9022741 to your computer and use it in GitHub Desktop.
Save bl0ckeduser/9022741 to your computer and use it in GitHub Desktop.
MARS recursive factorial
# MARS recursive factorial
# Sat Feb 15 12:50:25 EST 2014
.data
title: .asciiz "factorials\n==========\n\n"
nfactis: .asciiz "! is "
newline: .asciiz "\n"
.text
main:
addi $v0, $zero, 4 # print title
la $a0, title
syscall
add $s0, $zero, $zero # i = 0
loop:
add $a0, $zero, $s0 # call fact(i)
jal fact
add $s1, $zero, $v0 # save result to j
addi $v0, $zero, 1 # print i
add $a0, $zero, $s0
syscall
addi $v0, $zero, 4 # print "! is"
la $a0, nfactis
syscall
addi $v0, $zero, 1 # print j (result)
add $a0, $zero, $s1
syscall
addi $v0, $zero, 4 # print \n
la $a0, newline
syscall
addi $s0, $s0, 1 # ++i
slti $t0, $s0, 10 # t0 = i < 10
bne $t0, $zero, loop # loop if t0 != 0, i.e. if i < 10
############ end of loop #############
addi $v0, $zero, 10 # exit
syscall
fact:
###### make new stack frame ######
sub $sp, $sp, 8
sw $ra, 0($sp)
##################################
# n < 2 ?
slti $t0, $a0, 2
beq $t0, $zero, fact_recurse
# yes; fact(n) = 1 for n < 2
addi $v0, $zero, 1
j fact_end
# no; fact(n) = n * fact(n-1) for n >= 2
fact_recurse:
sw $a0, 4($sp) # save n to A0
sub $a0, $a0, 1 # n -= 1
jal fact # call fact(n-1)
lw $a0, 4($sp) # restore n to A0
mult $v0, $a0 # result = n * fact(n-1)
mflo $v0
fact_end:
# close stack frame and return
lw $ra, 0($sp)
add $sp, $sp, 8
jr $ra
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment