JimTom
JimTom

Reputation: 13

Mips: function trouble

Trying to create a function that so that f(0) = 8, and f(n) = 4f(n-1) - n + 5 if n > 0 recursively, but unable to get it to function correctly

 # $a0 = inpyt
 # $v0 = return value

f:     bnez  $a0, greaterthan0
       li $v0, 8
       jr $ra

greaterthan0: addi $sp,$sp,-8
              sw $ra, 0($sp) 
              sw $a0,4($sp)
              sub $t3,$a0,1 # n-1=n
              jal f

              lw $ra, ($sp)
              lw $a0, 4($sp)
              addi $sp,$sp,8
              sll $t0,$t3,2 # mul n-1 by 4
              sub $t1,$t0,$t3
              addi $t2,$t1,5 # add 5 to n
              jr $ra

Upvotes: 0

Views: 42

Answers (1)

Konrad Lindenbach
Konrad Lindenbach

Reputation: 4961

There are a few problems here.

The first problem here is that you are not following the convention that you have set out by passing the input in $a0 and returning the value in $v0.

To fix this, change sub $t3,$a0,1 # n-1=n to sub $a0,$a0,1 # n-1=n and addi $t2,$t1,5 # add 5 to n to addi $v0,$t1,5 # add 5 to n.

Next there are some math errors in which variables you picked to evaluate f(n-1) - n + 5.

First, the comment mul n-1 by 4 is fundamentally wrong as we in fact want to multiple f(n-1) by 4. After the recursive call returns, the value of f(n-1) is of course stored in $v0.

Below is my fix:

 # $a0 = inpyt
 # $v0 = return value

f:     bnez  $a0, greaterthan0
       li $v0, 8
       jr $ra

greaterthan0: addi $sp,$sp,-8
              sw $ra, 0($sp) 
              sw $a0,4($sp)
              sub $a0,$a0,1 # n=n-1
              jal f


              lw $ra, 0($sp)
              lw $a0, 4($sp)
              addi $sp,$sp,8

              sll $t0,$v0,2 # mul f(n-1) by 4
              sub $t1,$t0,$a0
              addi $v0,$t1,5 # add 5 to n
              jr $ra

Upvotes: 1

Related Questions