Wobblester
Wobblester

Reputation: 740

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

I know how to do it in c. Compute the square root, take the modulus 10 of the square root. if the modulus is 0 then it's a perfect square.

But how can I do it in assembly, since I can't do a square root in it. Is there an easier way?

Upvotes: 2

Views: 2605

Answers (3)

barak manos
barak manos

Reputation: 30136

You can implement it in C or C++, and then view the disassembly.

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.

Upvotes: 0

Seva Alekseyev
Seva Alekseyev

Reputation: 61378

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).

If you need help with the rest of the algorithm, e. g. copying general purpose registers to floating point ones, converting integer to float and back, FP arithmetic, please say so.

Upvotes: 0

MrSykkox
MrSykkox

Reputation: 528

Have you had a look at Newton's Method?

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

And floating point registers in mips

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

And another similar thread

Finding square root of an integer on MIPS assembly

Have you tried to do any coding yourself? And what is your assembly level?

Thanks.

Upvotes: 3

Related Questions