简体   繁体   English

确定整数是否是汇编中的完全平方数 (mips32)

[英]Determining if an integer is a perfect square in assembly (mips32)

I know how to do it in c.我知道如何在 c 中做到这一点。 Compute the square root, take the modulus 10 of the square root.计算平方根,取平方根的模数 10。 if the modulus is 0 then it's a perfect square.如果模数为 0,则它是一个完美的正方形。

But how can I do it in assembly, since I can't do a square root in it.但是我怎么能在汇编中做到这一点,因为我不能在其中做平方根。 Is there an easier way?有更容易的方法吗?

Have you had a look at Newton's Method?你看过牛顿法吗?

http://en.wikipedia.org/wiki/Newton 's_method http://en.wikipedia.org/wiki/Newton 's_method

And floating point registers in mips和 mips 中的浮点寄存器

http://en.wikipedia.org/wiki/MIPS_architecture#Floating_point http://en.wikipedia.org/wiki/MIPS_architecture#Floating_point

And another similar thread和另一个类似的线程

Finding square root of an integer on MIPS assembly 在 MIPS 程序集上查找整数的平方根

Have you tried to do any coding yourself?您是否尝试过自己进行任何编码? And what is your assembly level?你的装配水平是多少?

Thanks.谢谢。

Yes you can do square root in assembly.是的,你可以在组装中做平方根。 Square root of floating point numbers, that is.浮点数的平方根,即。 If your MIPS CPU supports floating point instructions (most of them do these days), it has the SQRT.D command (square root of double).如果您的 MIPS CPU 支持浮点指令(现在大多数都支持),它就有 SQRT.D 命令(double 的平方根)。

If you need help with the rest of the algorithm, eg copying general purpose registers to floating point ones, converting integer to float and back, FP arithmetic, please say so.如果您需要有关算法其余部分的帮助,例如将通用寄存器复制到浮点寄存器,将整数转换为浮点并返回,FP 算法,请说出来。

You can implement it in C or C++, and then view the disassembly.可以用C或C++实现,然后查看反汇编。

In order to do it efficiently, I suggest using an iterative binary search:为了有效地做到这一点,我建议使用迭代二进制搜索:

int isSquare(unsigned int num)
{
    unsigned int lo = 0;
    unsigned int hi = num;
    do
    {
        unsigned int mid = (hi+lo)/2;
        unsigned int square0 = mid*mid;
        unsigned int square1 = (mid+1)*(mid+1);
        if (num == square0 || num == square1)
            return 1;
        if (num < square0)
            hi = mid;
        else // if (num > square1)
            lo = mid;
    }
    while (lo+1 < hi);
    return 0;
}

Please note that any input to this function cannot be larger than 2^(num_of_bits_per_int/2+1)-3 .请注意,此函数的任何输入都不能大于2^(num_of_bits_per_int/2+1)-3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM