正如 Patricia 所说,计算 (2^a)^(1/b) 是有意义的。从您的 cmets 我看到 b 始终为 4。然后它变得简单得多。
因为你总是有 2 的幂,并且总是需要四方根,所以你可以将数字 a 分成 4 的部分(即2^4)和一个余数。其余的只能有 4 个值,为此,您可以使用查找表。我会将其编码为定点值,例如按2^16缩放。
所以,事实上,如果quotient = a // 4 和remainder = a % 4 你计算:2^(quotient) * (2^(remainder / 4) * 65536) // 65536,其中// 表示整数除法,/ 表示浮点除法(我知道这不是有效的 Java,但我使用不同的运算符来显示差异)。
这应该比使用 Newton-Raphson 重复计算平方根更快、更容易。
我不是很了解Java,所以如果语法不正确,请原谅,但它应该或多或少是这样的:
public class MyClass
{
public static int[] factors;
public static void initfactors()
{
factors = new int[4];
factors[0] = 65536; // 2^(0/4) * 65536
factors[1] = 77936; // 2^(1/4) * 65536
factors[2] = 92682; // 2^(2/4) * 65536
factors[3] = 110218; // 2^(3/4) * 65536
}
// Returns 2^(a/4) as integer
public static int calc(int a)
{
int quotient = a / 4;
int remainder = a % 4; // a == 4 * quotient + remainder
int factor = factors[remainder];
// calculate 2^(a/4) * (2^(remainder/4) * 65536) / 65536
return ((1 << quotient) * factor) >> 16;
}
因子可以这样求:你只需用计算器计算2^0、2^0.25、2^0.5、2^0.75,然后将结果乘以65536(2^16),最好四舍五入因此移位不会导致数字略低于您想要的值。
使用示例:
public static void main(String[] args)
{
initfactors();
int result = calc(31);
System.out.println(result);
}
你的例子:
quotient: 31 / 4 --> 7
remainder: 31 % 4 --> 3
factor: factors[3] --> 110218
result: ((1 << 7) * 110218) >> 16 --> 128 * 110218 / 65536 --> 215.