Search code examples
loopsmipsfactorial

How do you write code to do factorials in MIPS?


The problem states: Please write a loop to compute the factorial of a positive number currently stored in $t0 and store the result in $t1 in 4 instructions.

This is what I have so far I'm pretty sure it works but its in 6 instructions.

       li $t3, 1
       move $t1, $t0
       move $t2, $t0
 LOOP: addi $t2, $t2, -1
       mul $t1, $t1, $t2
       bne $t2, $t3, LOOP

Edit. Here's the solution

 li $t1 1 
 LOOP: mul $t1 $t1 $t0 
 addi $t0 $t0 -1 
 bgez $t0 LOOP 

Solution

  •  li $t1 1 
     LOOP: mul $t1 $t1 $t0 
     addi $t0 $t0 -1 
     bgez $t0 LOOP