csquare-root

fast integer square root approximation


I am currently searching for a very fast integer square root approximation, where floor(sqrt(x)) <= veryFastIntegerSquareRoot(x) <= x

The square root routine is used for calculating prime numbers, which get considerably faster if only values below or equals sqrt(x) are checked for being a divisor of x.

What I am currently having is this function from Wikipedia, adjusted a small bit to work with 64-bit integers.

Because I have no other function to compare against (or more precise, the function is too precise for my purposes, and it probably takes more time, than being higher than the actual result.)


Solution

  • Loopfree/jumpfree (well: almost ;-) Newton-Raphson:

    /* static will allow inlining */
    static unsigned usqrt4(unsigned val) {
        unsigned a, b;
    
        if (val < 2) return val; /* avoid div/0 */
    
        a = 1255;       /* starting point is relatively unimportant */
    
        b = val / a; a = (a+b) /2;
        b = val / a; a = (a+b) /2;
        b = val / a; a = (a+b) /2;
        b = val / a; a = (a+b) /2;
    
        return a;
    }
    

    For 64-bit ints you will need a few more steps (my guess: 6)