Factorial
Factorial
Andreas Klappenecker
September 15, 2004
Factorial Numbers. If you have n different objects, then you can arrange
them in n × (n − 1) × · · · × 2 × 1 ways. This number is called n factorial and is
usually written as n!. We give a simple example of a recursive MIPS assembly
language program that computes this number.
Our little program has the following structure:
1a hfac.asm 1ai≡
hstring definitions 2ci
.text
.globl main
hfactorial procedure 1bi
hmain procedure 2di
In the main procedure, we prompt the user to input an integer n ≥ 0, call the
factorial procedure fac with the argument n, and output the result. We present
the program in the literate programming style, where hchunki represents some
chunk of code that is explained in this document right after hchunki ≡.
1
September 15, 2004 factorial.nw 2
stack; therefore, after restoring the registers, we can be sure that the register
$a0 contains again the value n. The code to save the two registers is given by
2a hsave registers 2ai≡ (1b)
addiu $sp, $sp, -8 # make room for 2 registers on stack
sw $ra, 4($sp) # save return address register $ra
sw $a0, 0($sp) # save argument register $a0=n
and the code to restore the two registers by
2b hrestore registers 2bi≡ (1b)
lw $a0, 0($sp) # restore $a0=n
lw $ra, 4($sp) # restore $ra
addiu $sp, $sp, 8 # multipop stack
This example illustrates that recursive procedures are not difficult to implement
in the MIPS assembly language.