【问题标题】:Simple Java power recursion简单的 Java 幂递归
【发布时间】:2014-09-14 16:44:56
【问题描述】:

所以我正在制作的递归函数需要 2 个变量(xy)并计算 xy 的幂。就像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。 显然这是错误的,因为正确的答案不可能是否定的。

【问题讨论】:

  • 尝试使用 public long power(int x, int y) 代替
  • 可能的最大整数值是多少? 50^6 的值是多少? en.wikipedia.org/wiki/Integer_overflow
  • 成功了,谢谢!但为什么:D
  • 哦,我明白了,非常感谢。
  • @niana 因为蚂蚁不能吃大象 :-)

标签: java recursion int long-integer


【解决方案1】:

你的方法不错,但是对于太长的数字就不行了。

int 有 4 字节(32 位)=> 最大值为 21474836472^31-1),总计:2^32 值(也有一些负数)

long 有 8 字节(64 位)=> 最大值为 92233720368547758072^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!

【讨论】:

  • 很好的解释!我现在明白了,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2016-01-23
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 2015-11-08
  • 1970-01-01
  • 2016-05-08
相关资源
最近更新 更多