相关疑难解决方法(0)

使用位移找到整数平方根的最快方法是什么?

我一直在寻找计算数字(整数)的平方根(整数)的最快方法.我在维基百科中遇到了这个解决方案,它找到了一个数字的平方根(如果它是一个完美的正方形)或者它最近的下方完美正方形的平方根(如果给定的数字不是一个完美的正方形:

short isqrt(short num) {
    short res = 0;
    short bit = 1 << 14; // The second-to-top bit is set: 1L<<30 for long
    // "bit" starts at the highest power of four <= the argument.
    while (bit > num)
        bit >>= 2;
    while (bit != 0) {
        if (num >= res + bit) {
            num -= res + bit;
            res = (res >> 1) + bit;
        }
        else
            res >>= 1;
        bit >>= 2;
    }
    return res;
}
Run Code Online (Sandbox Code Playgroud)

我尝试了很多测试运行来跟踪算法,但我似乎并不理解里面的部分 …

bit-shift square-root memory-efficient

6
推荐指数
1
解决办法
4162
查看次数

标签 统计

bit-shift ×1

memory-efficient ×1

square-root ×1