I'm doing an assignment in MIPS and I feel like my logic is sound but I just can't get the code to produce the correct output. Can anyone look over what I've got and help? This is the corresponding function in C that I'm trying to implement.
int function1(int n) {
if (n <= 3) {
int ans1 = (3*n)-5;
return ans1;
}
else {
int ans1 = (n-1)*function1(n-1) + function1(n-2) - n;
return ans1;
}
}
This is what I've got in MIPS. For the sample output, when the user enters 8 the output is supposed to be 1096. I get 22,735 so obviously I'm messing up big time.
.data
message1: .asciiz "Enter an integer\n"
message2: .asciiz "The integer is: "
.text
.globl main
main:
la $a0, message1
li $v0, 4
syscall # print message1 string
li $v0, 5
syscall # get user input
move $a0, $v0 # int n
jal function # call function
move $s0, $v0 # save function return value
la $a0, message2
li $v0, 4
syscall # print message2 string
move $a0, $s0
li $v0, 1
syscall # print the solution computed by the recursive function
li $v0, 10
syscall # exit
function:
addi $sp, $sp, -12 # allocate memory on stack
sw $ra, 0($sp) # save return address
sw $a0, 4($sp) # save argument
ble $a0, 3, base_case # if n is <= 3 go to base case
addi $a0, $a0, -1 # n -= 1
jal function # recursive call
lw $a0, 4($sp) # load n
mul $v0, $v0, $a0 # (n-1) * function(n-1)
sw $v0, 8($sp) # save result
lw $a0, 4($sp) # load n
addi $a0, $a0, -2 # set n -= 2
jal function # recursive call
lw $t0, 8($sp) # load (n-1) * function(n-1)
add $v0, $v0, $t0 # add f(n-2) and (n-1) * f(n-1)
lw $t1, 4($sp) # load n
sub $v0, $v0, $t1 # (n-1) * f(n-1) + f(n-2) - n
lw $ra, 0($sp) # load return address
addi $sp, $sp, 12 # free stack
jr $ra # return
base_case:
li $t5, 3
mul $v0, $a0, $t5 # (n*3)
addi $v0, $v0, -5 # (n*3) - 5
lw $ra, 0($sp) # load return address
addi $sp, $sp, 12 # free stack
jr $ra # return