Advertisement
foreverfugazi

fact recursive

Oct 17th, 2024
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. .text
  2. li s0, 6 # Load 6 (input)
  3. mv a0, s0 # Move input to a0
  4. jal x1, fact # Call factorial function
  5. beq x0, x0, exit # End program
  6. fact:
  7. addi sp, sp, -8 # Stack space for s0, x1
  8. sw, s0, 0(sp) # Save s0
  9. sw, x1, 4(sp) # Save return address
  10. li t0, 3 # Load base case value
  11. blt a0, t0, skip_call # If a0 < 3, skip recursion
  12. mv s0, a0 # Store current a0
  13. addi a0, a0, -1 # a0 = a0 - 1
  14. jal x1, fact # Recursively call fact
  15. mul a0, a0, s0 # Multiply result with s0
  16. skip_call:
  17. lw s0, 0(sp) # Restore s0
  18. lw, x1, 4(sp) # Restore return address
  19. addi sp, sp, 8 # Clean up stack
  20. jalr x0, x1, 0 # Return
  21. exit:
  22. nop # Program end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement