Pages

March 14, 2012

MIPS - Factorial Code


Here is another MIPS problem :  
Write a program to compute x ! (factorial)

The simplest way to implement this using MIPS assembly language is by using a loop that decrement the x number by one ($t1), and multiply it with the x ($t0). Then the decremented number ($t1) will be decremented again and multiplied again with the previously multiplied number ($t3). This is repeated until the multiplier ($t1) reach number one. The result then be stored in the memory. There is no special intention of me by not using the $t2 register, I just forget that I haven't use register $t2.

Here is the code:
.data 0x10010000
fact: .space 4
.text
.globl main

main: addu $s0, $ra, $0
lui $s1,0x1001 
ori $t0,$0,12
ori $t4,$0,1
addi $t1,$t0,-1
mul $t3,$t1,$t0

loop: beq $t1,$t4,slese
addi $t1,$t1,-1
mul $t3,$t3,$t1
j loop

slese: sw $t3,0($s1)
addu $ra,$0,$s0
jr $ra 

No comments:

Post a Comment