LordMirai

mips lab 5 - recursivity - factorial

Mar 23rd, 2023
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. .data
  2.  
  3. # factorial(n):
  4. # if n == 0:
  5. # return 1
  6. # return n * factorial(n-1)
  7.  
  8. startText: .asciiz "Enter a number\n n = "
  9. endText: .asciiz "n! = "
  10. invalidText: .asciiz "Invalid number."
  11.  
  12. .text
  13.  
  14. start:
  15. puts startText # print the text
  16. geti $a0 # get the number
  17.  
  18. bltz $a0, textIsInvalid # if the number is negative, print the error message and exit
  19.  
  20. # -----------------
  21. # before the call
  22. # $ra, $fp, $a0 -- the order is important
  23. subu $sp, $sp, 12 # allocate space for the return address. 12 = 4 * 3 (3 registers) [unsigned subtraction]
  24. sw $ra, 8($sp) # save the return address. Decrementing offset since we're going *DOWN* the stack
  25. sw $fp, 4($sp) # save the frame pointer
  26. # sw, $a0, 0($sp) # we do NOT need to save $a0 because it's done automatically by the jal instruction. Doing so doesn't break anything, but it's redundant.
  27.  
  28. addu $fp, $sp, 12 # move FP to the base again.
  29.  
  30. # -----------------
  31.  
  32.  
  33. jal Factorial # call the factorial function
  34.  
  35. # after the call
  36. addu $sp, $sp, 12 # pop all the registers we pushed before the call
  37.  
  38. display:
  39. puts endText
  40. puti $v1
  41.  
  42. j finish
  43.  
  44. textIsInvalid:
  45. puts invalidText
  46. j finish
  47.  
  48. finish:
  49. done
  50.  
  51.  
  52. Factorial:
  53.  
  54.  
  55. subu $sp, $sp, 12 # Same steps as above.
  56. sw $ra, 8($sp)
  57. sw $fp, 4($sp)
  58. sw $a0, 0($sp) # we DO need to save it now
  59.  
  60. addu $fp, $sp, 12
  61.  
  62. lw $v1, ($sp) # v1 = n
  63.  
  64. bgtz $v1, continue # if n > 0, continue
  65.  
  66.  
  67. li $v1, 1 # else, v1 = 1 (return 1)
  68. j func_finish
  69.  
  70.  
  71.  
  72.  
  73. continue:
  74. lw $a0, 0($sp) # a0 = n
  75. sub $a0, $a0, 1 # a0 = n - 1
  76.  
  77. jal Factorial # call factorial(n-1)
  78.  
  79. lw $a0, ($sp) # a0 = n
  80. mul $v1, $v1, $a0 # v1 = v1 * a0 (v1 = n * factorial(n-1))
  81.  
  82.  
  83. func_finish:
  84. lw $ra, 8($sp) # restore the return address
  85. lw $fp, 4($sp) # restore the frame pointer
  86. addu $sp, $sp, 12 # pop all the registers we pushed before the call
  87.  
  88. jr $ra
  89.  
  90.  
Advertisement
Add Comment
Please, Sign In to add comment