java - 简单的 Java 幂递归

标签 java recursion int long-integer

因此,我正在制作的递归函数需要 2 个变量( xy )并计算 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 = 15625000000 是有效的 long 数字,但不是有效的 int(它大于 2^32-1 )

小心:

如果您尝试使用更长的数字,您也可能会遇到 long 问题。 例如:

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!

关于java - 简单的 Java 幂递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25835595/

相关文章:

java - 包含多个图像的幻灯片放映?

具有递归功能的中国环

python - Python 中的可变函数调用

php - 使用 PHP int 的开销是多少?

string - 类型转换错误

java - 如何删除表中的值? (MVN、Spring、Java)

java - Springockito如何?

java - 对象数组的正确使用方法?

java - java中比较多个整数并找到最大的

json - 试图解析递归 JSON,我在正确的轨道上吗?