简单Java幂递归
因此,我所做的递归函数取两个变量(简单Java幂递归,java,recursion,int,long-integer,Java,Recursion,Int,Long Integer,因此,我所做的递归函数取两个变量(x和y),并将x计算为y的幂。就像Math.pow函数一样y是正的,所以我不需要担心负指数。 这是我的代码: public static int power(int x, int y) { if (y == 0) return 1; else return x * power(x, y-1); } 起初,它似乎工作正常,但后来我尝试输入power(
x
和y
),并将x
计算为y
的幂。就像Math.pow
函数一样y
是正的,所以我不需要担心负指数。
这是我的代码:
public static int power(int x, int y) {
if (y == 0)
return 1;
else
return x * power(x, y-1);
}
起初,它似乎工作正常,但后来我尝试输入power(50,6)
。我得到了-1554869184
。
显然,这是错误的,因为正确的答案不能是否定的。您的方法很好,但它不适用于太长的数字
int
有4个字节(32位)=>最大值为2147483647
(2^31-1
),总计:2^32
值(也有一些负数)
long
有8个字节(64位)=>最大值为9223372036854775807
(2^63-1
),总计:2^64
值
这些值可以通过以下方式在Java中找到:
Integer.MAX_VALUE // Integer and int have the same range
Long.MAX_VALUE // Long and long have also the same range
对于您的情况:
50^6=156500000
是有效的long
数字,但不是有效的int
(大于2^32-1
)
小心点:
如果您试图使用更长的数字,则long
也会出现问题。
例如:
尝试使用公共长幂(intx,inty)代替可能的最大整数值是什么?50^6的值是多少?成功了,谢谢!但为什么:我明白了,非常感谢。@niana因为蚂蚁不能吃大象:-)很好的解释!我现在明白了,非常感谢。
power(10,18); // OK
power(10,19); // not OK: negative number
power(10,20); // not OK: even if the number is positive
// the answer is not good - it has only 18 digits!