1.遍历法
.data
prompt:.asciiz "\n input a value:"
result:.asciiz "\n the square root is : "
.text
main:
li $v0,4
la $a0,prompt
syscall
li $v0,5
syscall
move $t0,$zero
move $t1,$v0
srl $t2,$v0,1 # input / 2
addi $t2,$t2,1
while:
bgt $t0,$t2,out
mul $t3,$t0,$t0
beq $t3,$t1,end
addi $t0,$t0,1
b while
out:
li $v0,4
la $a0,result
syscall
move $a0,$t0
li $v0,1
syscall
b exit
end:
li $v0,4
la $a0,result
syscall
li $v0,1
move $a0,$t0
syscall
exit:
li $v0,10
syscall
时间复杂度 O(n)
2.二分搜索法
.data
prompt:.asciiz "\n input a value:"
result:.asciiz "\n the square root is : "
.text
main:
li $v0,4
la $a0,prompt
syscall
li $v0,5
syscall
move $t0,$zero
move $t1,$v0
addi $t2,$zero,0
srl $t3,$t1,1
while:
add $t5,$t2,$t3
srl $t5,$t5,1
mul $t4,$t5,$t5
beq $t1,$t4,out
blt $t4,$t1,less
bgt $t4,$t1,bigger
b while
less:
move $t2,$t5
b while
bigger:
move $t3,$t5
b while
out:
li $v0,4
la $a0,result
syscall
li $v0,1
move $a0,$t5
syscall
li $v0 ,10
syscall
时间复杂度 O(logn)