Silver_Smoulder icon

[ASM][Imperfect]Hailstone Sequence

Silver_Smoulder | PRO | 05/09/19 02:33:41 PM UTC | 0 ⭐ | 376 👁️ | Never ⏰ | []
text |

1.81 KB

|

None

|

0 👍

/

0 👎

#1 - user inputs their number
#2 - shove it into a function
#3a - IF number is even (mod 2 = 0) then divide it by 2 and store it
#3b - else multiply by 3, add 1, and store it
#4a - output number, then a comma space, and take that number and feed it into the function again
#5 - exit condition is when the number reaches the value of 1
 .globl main
.text
 main:
	#initiate the first number
	li $v0, 4 #string output
	la $a0, prompt
	syscall
 	li $v0, 5 #prep for user input
	syscall
	move $t0, $v0 #store in $t0
 	jal hailstone #go to the main function
         li $v0, 10
	syscall
	#just terminate the sequence with no extra words
hailstone:
	#lower the stack by 4 here
	rem $t1, $t0, 2 #test to see if the number is divisible by 2
	beqz $t1, even #if there is no remainder, the number is divisible by 2, and we go to even
 	#if it's not even, it's odd and we can go ahead with the rest of the function
 	#output the number
	move $a0, $t0
	li $v0, 1 #integer output
	syscall #do it
	move $t0, $a0 #put the number back
	li $v0, 4
	la $a0, comma_space #load a ', ' behind the integer so that it's readable
	syscall 
 	#test to see if the number is our exit condition
	ble $t0, 1, exit
 	mul $t0, $t0, 3 #if the number is odd, then we multiply by 3...
	addi $t0, $t0, 1 #...then add 1 and our original number is modified
 	jal hailstone
 	#jr $ra #go back to hailstone
 even:
	#output the number
	move $a0, $t0
	li $v0, 1 #integer output
	syscall #do it
	move $t0, $a0 #put the number back
	li $v0, 4
	la $a0, comma_space #load a ', ' behind the integer so that it's readable
	syscall 
 	div $t0, $t0, 2 #divide the number by 2 and store it in the same place
 	jal hailstone
   exit:
	jr $ra 
  .data
prompt: 
	.asciiz "Please enter your initial number: "
comma_space:
	.asciiz ", "

Comments