Computer Engineering Project Collection

-->

Saturday, February 14, 2009

MIPS - Factorial

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

Labels: , , , , ,

1 Comments:

  • I am trying to get this to work but I could not get it to work. For instance if I want to compute 4!, do I store it in $t1?

    I was trying to use this example to compute (2* ! N ) where ! is the factorial of a given positive integer N using loop. Could you help me out with this?

    By Blogger Unknown, At 6:16 AM  

Post a Comment

Subscribe to Post Comments [Atom]



<< Home