## Tuesday, March 24, 2009

### To Find a Square-root with miniMIPS

###############################################################################
# To find a square-root of an integer
# (c) M. Lutfi, 2009
#
# Platform: miniMIPS
# tested on: MARS simulator
#
# Convention:
# \$v0..\$v1,\$t0..\$t9,\$a0: destroyed during procedure calls
# \$s0..\$s9: saved during procedure calls
###############################################################################

.text
main:
la \$a0, question
jal print_string # print(question)
add \$s0,\$v0,\$zero # s0 = x
bltu \$s0,\$zero,error # exit if x <>
beqz \$s0,just_print # print "0" if x == 0
beq \$s0,1,just_print # print "1" if x=1

addi \$t1,\$zero,0 # a = 0
add \$t2,\$s0,\$zero # b = x

loop:
add \$t3,\$t1,\$t2 # t3 = (a+b)
sra \$t3,\$t3,1 # mid = (a+b)/2
beq \$t3,\$t1,print_sqrt
beq \$t3,\$t2,print_sqrt # to prevent endless loop and give approx. result
multu \$t3,\$t3 #(hi,lo) = mid*mid
mflo \$t4
mfhi \$t5 # (t5,t4) = mid^2
beq \$t4,\$s0,print_sqrt # if (mid^2 == x) goto print_sqrt
bgtu \$t4,\$s0,set_b # if (mid^2 > x) goto set_b
bltu \$t4,\$s0,set_a # if (mid^2 <>

set_a:
add \$t1,\$t3,\$zero # a = mid
j loop

set_b:
add \$t2,\$t3,\$zero # b = mid
j loop

print_sqrt:
jal print_string # print "sqrt(x) = "
add \$a0,\$t3,\$zero # mid is the sqrt(x)
jal print_integer # print the result
j main # do it again. To finish, just enter neg number
j exit

error:
la \$a0, inv_num
syscall
j exit

just_print:
jal print_string # print "sqrt(x) = "
jal print_integer

exit: # no param needed
syscall # exit

#---------------------------------subroutines----------------------------------
print_string: # string address in a0
addi \$v0,\$zero,4 # a0 and v0 are destroyed
syscall
jr \$ra

print_integer: # integer value in a0
syscall
jr \$ra

#-------------------data section-----------------

.data

question: .asciiz "\nEnter number to be square-rooted: "
inv_num: .asciiz "\nInvalid number (e.g, negative"