spimB-2

.data
str1: .asciiz "Enter int-number:"
ans1: .asciiz "square:"
ans2: .asciiz "square root:"
Unsuitable_text: .asciiz "! The square root of a negative number does not exist !"
eol: .asciiz "\n"
.text
.globl main


main:
li $v0, 4
la $a0, str1
syscall

li $v0, 5
syscall
move $a1, $v0
mul $t0, $a1, $a1

li $v0, 4
la $a0, ans1
syscall
li $v0, 1
move $a0, $t0
syscall
li $v0, 4
la $a0, eol
syscall

bgt $zero, $a1, Unsuitable
jal sqrt
move $t1, $v0

li $v0, 4
la $a0, ans2
syscall
li $v0, 1
move $a0, $t1
syscall
li $v0, 4
la $a0, eol
syscall
j main


Unsuitable:
li $v0, 4
la $a0, Unsuitable_text
syscall
la $a0, eol
syscall
j main

sqrt:
move $v0, $zero
sqrt_loop:
mul $t0, $v0, $v0
bgt $t0, $a1, exit
addi $v0, $v0, 1
j sqrt_loop
exit:
addi $t1, $v0, -1
mul $t1, $t1, $t1
sub $t0, $a1, $t0 # $t0 > $a1 なので負の数
sub $t1, $a1, $t1 # $t1 < $a1 なので正の数
add $t2, $t0, $t1 # $t1の絶対値が小さければ負=>$v0 - 1がより近似解,$t0の絶対値が小さければ正=>$v0 - 0がより近似解
slti $t0, $t2, 0 # $t2が負ならば1、正ならば0を返す
sub $v0, $v0, $t0 # $v0と$v0 ー 1 の近似解が得られる
jr $ra