Silver_Smoulder

[ASM][Imperfect]Hailstone Sequence

May 9th, 2019
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. #1 - user inputs their number
  2. #2 - shove it into a function
  3. #3a - IF number is even (mod 2 = 0) then divide it by 2 and store it
  4. #3b - else multiply by 3, add 1, and store it
  5. #4a - output number, then a comma space, and take that number and feed it into the function again
  6. #5 - exit condition is when the number reaches the value of 1
  7.  
  8. .globl main
  9. .text
  10.  
  11. main:
  12. #initiate the first number
  13. li $v0, 4 #string output
  14. la $a0, prompt
  15. syscall
  16.  
  17. li $v0, 5 #prep for user input
  18. syscall
  19. move $t0, $v0 #store in $t0
  20.  
  21. jal hailstone #go to the main function
  22.  
  23. li $v0, 10
  24. syscall
  25. #just terminate the sequence with no extra words
  26. hailstone:
  27. #lower the stack by 4 here
  28. rem $t1, $t0, 2 #test to see if the number is divisible by 2
  29. beqz $t1, even #if there is no remainder, the number is divisible by 2, and we go to even
  30.  
  31. #if it's not even, it's odd and we can go ahead with the rest of the function
  32.  
  33. #output the number
  34. move $a0, $t0
  35. li $v0, 1 #integer output
  36. syscall #do it
  37. move $t0, $a0 #put the number back
  38. li $v0, 4
  39. la $a0, comma_space #load a ', ' behind the integer so that it's readable
  40. syscall
  41.  
  42. #test to see if the number is our exit condition
  43. ble $t0, 1, exit
  44.  
  45. mul $t0, $t0, 3 #if the number is odd, then we multiply by 3...
  46. addi $t0, $t0, 1 #...then add 1 and our original number is modified
  47.  
  48. jal hailstone
  49.  
  50. #jr $ra #go back to hailstone
  51.  
  52. even:
  53. #output the number
  54. move $a0, $t0
  55. li $v0, 1 #integer output
  56. syscall #do it
  57. move $t0, $a0 #put the number back
  58. li $v0, 4
  59. la $a0, comma_space #load a ', ' behind the integer so that it's readable
  60. syscall
  61.  
  62. div $t0, $t0, 2 #divide the number by 2 and store it in the same place
  63.  
  64. jal hailstone
  65.  
  66.  
  67.  
  68. exit:
  69. jr $ra
  70.  
  71.  
  72. .data
  73. prompt:
  74. .asciiz "Please enter your initial number: "
  75. comma_space:
  76. .asciiz ", "
Advertisement
Add Comment
Please, Sign In to add comment