int factorial (int n) { if (n <1) return 1; else return (n*factorial(n-1)); }
fact: addi $sp, $sp, -8 sw $ra, 4($sp) # save $ra slti $t0, $a0, 1 # n < 1? beq $t0, $zero, L1 addi $v0, $zero, 1 # return 1 addi $sp, $sp, 8 # fix up the stack pointer & return jr $ra L1: sw $a0, 0($sp) # save argument $a0 addi $a0, $a0, -1 # n = n-1 jal fact # jal(n-1) lw $a0, 0($sp) # restore argument $a0 mul $v0, $a0, $v0 # return n*fact(n-1) lw $ra, 4($sp) # restore $ra addi $sp, $sp, 8 # restore stack pointer jr $ra # return to the caller
沒有留言:
張貼留言