www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Integer Square Root

reply "Mike James" <foo bar.com> writes:
Would it be more useful to have a true integer square root rather than 
overloading the real square root? Something like:

T intsqrt(T)(T i) {
    T bitMask = 1;
    T result = 0;

    bitMask <<= T.sizeof * 4 - 1;

    while (bitMask) {
        result |= bitMask;
        if ((result * result) > i) {
            result &= ~bitMask;
        }
        bitMask >>= 1;
    }

    return result;
}


-=mike=- 
Aug 12 2010
parent Don <nospam nospam.com> writes:
Mike James wrote:
 Would it be more useful to have a true integer square root rather than 
 overloading the real square root? 
cast(int)sqrt() is MUCH quicker than any other way of doing it. Note that overloading sqrt is a temporary hack. BTW, your code fails for intsqrt(0x8000 * 0x8000) and higher.
Aug 12 2010