【MIPS汇编简单算法实例 Lab2】整数的平方根(遍历法、二分搜索法)

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)

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值