我正在寻找一些平方根计算算法,并找到了这个源文件。我想尝试复制它,因为它看起来很简单,但我无法将它与一些已知算法(牛顿,巴比伦......)联系起来。你能告诉我这个名字吗?
int sqrt(int num) {
int op = num;
int res = 0;
int one = 1 << 30; // The second-to-top bit is set: 1L<<30 for long
// "one" starts at the highest power of four <= the argument.
while (one > op)
one >>= 2;
while (one != 0) {
if (op >= res + one) {
op -= res + one;
res += 2 * one;
}
res >>= 1;
one >>= 2;
}
return res;
}
答案 0 :(得分:2)
作为@Eugene Sh.引用,这是经典的&#34;逐位数字&#34;用来计算平方根的方法。当在小学教授这些事情的时候,在base 10学到了它。
OP的代码也失败了选择号码。 sqrt(1073741824) --> -1
而不是预期的32768。1073741824 == 0x40000000
。此外,它大多数(全部?)值都失败了。当然,OP sqrt(some_negative)
也是一个问题。
候选人替代方案:here
unsigned isqrt(unsigned num) {
unsigned res = 0;
// The second-to-top bit is set: 1 << 30 for 32 bits
// Needs work to run on unusual platforms where `unsigned` has padding or odd bit width.
unsigned bit = 1u << (sizeof(num) * CHAR_BIT - 2);
// "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; // Key dif between this and OP's code
} else {
res >>= 1;
}
bit >>= 2;
}
return res;
}
可移植性更新。需要4的最大力量。
#include <limits.h>
// greatest power of 4 <= a power-of-2 minus 1
#define POW4_LE_POW2M1(n) ( ((n)/2 + 1) >> ((n)%3==0) )
unsigned bit = POW4_LE_POW2M1(UINT_MAX);