Equay
Equay

Reputation: 73

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 

Upvotes: 3

Views: 21626

Answers (4)

M. Ajwad Alam
M. Ajwad Alam

Reputation: 11

li $s1, 1
LOOP: mul $s1, $s1, $s0
addi $s0, $s0, -1
bgtz $s0, LOOP

The bgez will be bgtz (branch if grater than 0) bgez causes the factorial to multiply with 0 and returns 0.

Upvotes: 1

Amit Kesari
Amit Kesari

Reputation: 45

Works good on qtspim. All lines have small comments for better understanding.

Remember that when calling a function we should store it temporarily in stack so that even if the function changes register values we still have our data from previous main function.

    .data
    Enter: .asciiz "Enter value of n: \n"

    .text
    .globl main

main:
    lui $s0, 0x1001

    li $v0, 4                   # print message for i/p
    la $a0, Enter
    syscall

    li $v0, 5                   # get n
    syscall

    add $s1, $v0, $zero         # init n = 5
    li $s2, 1                   # s2 = 1 for base case
    
    add $a0, $s1, $zero         # pass fib(a0)
    jal factorial

    li $v0, 1                   # print result
    add $a0, $v1, $zero
    syscall

    li $v0, 10                  # exit
    syscall

factorial:
    addi $sp, $sp, -8           # grow sp below
    sw $a0, 0($sp)              # store arguments and return addr
    sw $ra, 4($sp)

    bne $a0, $s2, recursion     # n != 1
    add $v1, $s2, $zero
    addi $sp, $sp, 8            # restore $sp and remove stack frame
    jr $ra

    recursion: 
        addi $a0, $a0, -1       # fib(a0 - 1)
        jal factorial

        lw $a0, 0($sp)          # load back a0 to use as a0 * fib(a0-1)
        lw $ra, 4($sp)
        addi $sp, $sp, 8        
        mul $v1, $a0, $v1 

        jr $ra

Upvotes: 0

Hammad Mughal
Hammad Mughal

Reputation: 1

 .data

 msg: .asciiz "Enter a number"
 answer: .asciiz "\nFactorial is: "

 .text


 li $v0, 4
 la $a0, msg
 syscall

 li $v0, 5
 syscall


 move $a0, $v0
 li $v0, 1
 syscall

 jal calculate_factorial
 move $a1, $v0

 li $v0, 4
 la $a0, answer
 syscall

 move $a0, $a1
 li $v0, 1
 syscall

   li $v0, 10
   syscall

    calculate_factorial:
       addi $sp, $sp-4
       sw $ra, ($sp)

       li $v0, 1
       multiply:
        beq $a0, $zero, return
        mul $v0, $v0, $a0
        addi $a0, $a0, -1
        j multiply

    return:
    lw $ra, ($sp)
    jr $ra

Upvotes: 0

Equay
Equay

Reputation: 73

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

Upvotes: 3

Related Questions