Roc*_*net 14 algorithm math optimization
这是计算整数平方根的简单方法:
int isqrt(int num)
{
int root=0;
int b = 0x8000;
int a=0, c=0;
while (b) {
c = a|b;
if (c*c <= num)
a |= b;
b >>= 1;
}
}
Run Code Online (Sandbox Code Playgroud)
巧妙地(感谢维基百科),这可以像这样进行优化:
int sqrt(short num)
{
int op = num;
int res = 0;
int one = 1 << 30;
while (one > op)
one >>= 2;
while (one != 0) {
if (op >= res + one) {
op -= res + one;
res = (res >> 1) + one;
}
else
res >>= 1;
one >>= 2;
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
我的问题:是否可以为整数多维数据集根编写类似优化的算法?(这是在一个不喜欢乘法的小型微控制器上运行的)
根据这个 SO问题和标记的答案,从Hacker's Delight书中你可以找到这个实现:
int icbrt2(unsigned x) {
int s;
unsigned y, b, y2;
y2 = 0;
y = 0;
for (s = 30; s >= 0; s = s - 3) {
y2 = 4*y2;
y = 2*y;
b = (3*(y2 + y) + 1) << s;
if (x >= b) {
x = x - b;
y2 = y2 + 2*y + 1;
y = y + 1;
}
}
return y;
}
Run Code Online (Sandbox Code Playgroud)