查找有关MIPS汇编整数的平方根 [英] Finding square root of an integer on MIPS assembly

查看:190
本文介绍了查找有关MIPS汇编整数的平方根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我究竟能找到使用MIPS汇编整数的平方根?

hey how exactly can I find the square root of an integer using MIPS assembly?

推荐答案

我们可以像使用提交的的这个问题,并根据需要修改它。进入MIPS之前,让我们来看看用C实现:

We can use an algorithm like the one submitted for this question and adapt it as needed. Before getting into MIPS, lets look at an implementation in C:

//Function to compute sqroot(n)
int sqroot(int n) {
        int x = n;
        for (int i = 0; i < (n/2); i++)
             x = (x + n / x) / 2;

        return x;
}

sqroot(N)函数计算,相等于 N 的平方根的地板整数。所以,如果你要调用 sqroot(225)你会得到15不如预期,但 sqroot(15)将返回3,而不是3.87298。

The sqroot(n) function will compute and integer equivalent to the floor of the square root of n. So if you were to call sqroot(225) you would get 15 as expected, but sqroot(15) would return 3 instead of 3.87298.

从C code,我们可以勾勒出MIPS code将是什么样子:

From the C code, we can outline what the MIPS code will look like:

In calling function:
    Load the number to be squared into $a0
    jal root

root:
    Initialize $t0 = n, $t1 = i = 0, $t2 = x = n = $a0, $t3 = n/2

Loop:
    Divide n/x
    Add x to n/x
    Divide (x + n/x) by 2
    Check if $t1 < $t3
    If it is, branch back to loop
    Else, move x into return register $v0

请注意:


  1. 一定要推,并根据需要弹出堆栈。我离开是出于对简单性。

  2. 当2的功率分配,可以使用SRL指令。

  3. 有关澄清和说明MIPS的更多信息,请请点击

  1. Be sure to Push and Pop the stack as needed. I left that out for simplicity.
  2. When dividing by a power of 2, you can use the srl instruction.
  3. For clarification and additional information on MIPS instructions, click here.

这篇关于查找有关MIPS汇编整数的平方根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆