Java 我需要编写只返回整数幂的方法

Java 我需要编写只返回整数幂的方法,java,Java,我需要用java编写一个只返回整数幂的方法,并且我希望此方法返回-1,或者在数字超过integer.MAX_值时引发异常: 我尝试了第一个简单的步骤: public static int GetPower(int base, int power) { int result = 1; for(int i = 1; i<=power; i++) { result *= base; if (result < 0 ) {

我需要用java编写一个只返回整数幂的方法,并且我希望此方法返回-1,或者在数字超过integer.MAX_值时引发异常:

我尝试了第一个简单的步骤:

public static int GetPower(int base, int power)
{
    int result = 1;

    for(int i = 1; i<=power; i++)
    {
        result *= base;
        if (result <  0 ) {
            break; // not very acurate
        }
    }
    if (result < 0 ) {
        return -1;
    }
    return result;
}
publicstaticintgetpower(intbase,intpower)
{
int结果=1;

对于(int i=1;i您检查的是错误的。请使用1尝试您的方法。您注意到的效果是一个数字溢出。 如果将一个值添加到
Integer.MAX\u VALUE
中,将得到
Integer.MIN\u VALUE

现在您需要的是更多的空间来存储您的值。因为您想在32位整数空间内工作,所以您需要下一个更大的值。这将是一个64位
值。无论如何,这比任何
大小数
用法都要快

如果您的值超过了Integer.MAX\u value,您只需在任何循环步骤中进行检查,如果出现这种情况,则取消它

因此,生成的代码如下所示:

public static int GetPower(int base, int power)
{
    long result = 1;

    for(int i = 1; i <= power; i++)
    {
        result *= base;
        if (result > Integer.MAX_VALUE) {
            return -1;
        }
    }
    return result;
}
publicstaticintgetpower(intbase,intpower)
{
长期结果=1;
对于(int i=1;i整数.MAX_值){
返回-1;
}
}
返回结果;
}

此外,我建议您验证函数的输入,以确保基数不为负。

如果基数只能为正整数,则您的方法将有效。可能会出现下溢。您的基数为负整数,幂为奇数

处理这种情况的一种简单但不是最佳的方法是使用长数据类型来存储输出,并比较输出以检查它是否在Integer.MAX_值和Integer.MIN_值之间

public static int GetPower(int base, int power){
 long result = 1;

 for(int i = 1; i <= power; i++)
 {
    result *= base;
    if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
        return -1;
    }
 }
 return result;
}
publicstaticintgetpower(intbase,intpower){
长期结果=1;
对于(int i=1;i Integer.MAX|u值| result
Nitram和Pytalye的答案有效,但我不喜欢使用其他数据类型检查边界的想法。相反,我建议您使用以下简单检查:

// This basically means result * base > boundary
if ((base > 0 && result > (Integer.MAX_VALUE / base))
   || (base < 0 && result < (Integer.MIN_VALUE / -base)) // Negative base case
{
    return -1;
}
//这基本上是指结果*base>边界
if((基>0&&result>(Integer.MAX\u值/基))
||(基<0&&result<(Integer.MIN_VALUE/-base))//负基情况
{
返回-1;
}
因此,代码应该是:

public static int GetPower(int base, int power)
{
    int result = 1;

    for(int i = 1; i<=power; i++)
    {
        if ((base > 0 && result > (Integer.MAX_VALUE / base))
           || (base < 0 && result < (Integer.MIN_VALUE / -base)) {
            return -1;
        }

        result *= base;
    }

    return result;
}
publicstaticintgetpower(intbase,intpower)
{
int结果=1;
对于(int i=1;i 0&&result>(Integer.MAX_VALUE/base))
||(基<0&&result<(Integer.MIN_VALUE/-base)){
返回-1;
}
结果*=基数;
}
返回结果;
}

由于您有方法pow的简单实现,它不接受负数或负值,我的建议是创建允许的最高值,只需检查您的结果是否小于它

public static int getPower(int base, int power)
    {
        int result = 1;
        int maxAllowed = Integer.MAX_VALUE / base;

        for(int i = 1; i<=power; i++)
        {
            result *= base;
            if (i!=power && result>=maxAllowed){
                return -1;
            }

        }

        return result;
    }
publicstaticintgetpower(intbase,intpower)
{
int结果=1;
int maxAllowed=Integer.MAX_值/基数;
for(int i=1;i=maxAllowed){
返回-1;
}
}
返回结果;
}

但总的来说,我强烈建议不要重新发明轮子,而要使用
Math.pow
method

在java.lang.Math中已经有一个完全可行的幂函数。我强烈建议利用它来覆盖边缘情况

public class GetPower {

    public static int getPower(int base, int power) {
        double result = Math.pow(base, power);
        // check result in range
        if (result > Integer.MAX_VALUE)
            return -1;
        if (result < Integer.MIN_VALUE)
            return -1;
        return (int) result;
    }

    public static void main(String[] args) {
        for (int base=0; base<=10; ++base) {
            for (int power=0; power<=10; ++power) {
                int result = getPower(base, power);
                System.out.println("getPower(" + base + ", " + power + ") = " + result);
            }
        }
    }

}
公共类GetPower{
公共静态int-getPower(int-base,int-power){
双重结果=数学功率(基数、功率);
//检查范围内的结果
如果(结果>整数最大值)
返回-1;
if(结果<整数最小值)
返回-1;
返回(int)结果;
}
公共静态void main(字符串[]args){

对于(int base=0;base,如前所述,使用“更大”的数据类型可以进行验证并简化计算-但是如果没有更大的数据类型呢

如果会导致溢出,您可以进行数学测试:

如果您正在计算
base^power
,这意味着
base^power=result
-它还意味着
result的次方幂=base
-允许的最大结果是
整数。最大值
-否则您有溢出

大于零的任何数字的
次方根
始终在范围内
]0,数字]
-没有算术溢出的可能性

那么-让我们将您使用的
整数的
次方根
进行比较。MAX_值
-是
更大?然后您将遇到溢出-否则它将粘在
整数的结果下面(或等于
整数的结果)。MAX_值

private static double powSafe(double base, int pow){
    //this is the p-th root of the maximum integer allowed
    double root = Math.pow(Integer.MAX_VALUE, 1.0/pow); 

    if (root < base){
        throw new ArithmeticException("The calculation of " + base + "^" + pow + " would overflow.");
    }else{
        return Math.pow(base, pow);
    }
}

public static void main(String[] argv)
{
    double rootOfMaxInt = Math.pow(Integer.MAX_VALUE, 1.0/2);
    try{
        //that should be INTEGER.MAX_VALUE, so valid.
        double d1 = powSafe(rootOfMaxInt, 2);  
        System.out.println(rootOfMaxInt + "^2 = " + d1);
    }catch (ArithmeticException e){
        System.out.println(e.getMessage());
    }

    try{
        //this should overflow cause "+1"
        double d2 = powSafe(rootOfMaxInt +1, 2); 
        System.out.println("("rootOfMaxInt + "+ 1)^2 = " + d1);
    }catch (ArithmeticException e){
        System.out.println(e.getMessage());
    }

    double the67thRootOfMaxInt = Math.pow(Integer.MAX_VALUE, 1.0/67);
    try{
        //and so, it continues
        double d3 = powSafe(the67thRootOfMaxInt, 67); 
        System.out.println(the67thRootOfMaxInt + "^67 = " + d3);

        double d4 = powSafe(the67thRootOfMaxInt +1, 67); 
        System.out.println("(" + the67thRootOfMaxInt + " + 1)^67 = " + d3);

    }catch (ArithmeticException e){
        System.out.println(e.getMessage());
    }
}   

请注意,会出现不精确的情况,因为double没有无限精度,它已经截断了表达式
整数的第二个平方。Max_Value
,cause
Integer。Max_Value
是奇数。

您可以将基和幂转换为
大小数
,然后将结果与
整数进行比较。Max_Value
@user902383,而您完全有权处理案例
int
(您可以使用
bigint
进行验证)那么,如何处理
bigints
这个问题会很有趣?或者,您可以将Integer.MAX_值除以基数,然后在结果大于该值时返回error@dognose
biginger
受内存限制。如果
power
是一个负整数值,该怎么办?Ha.如果要允许
为负值这个答案比我的好。这实际上不起作用。例如,如果
base
为负值,则
(Integer.MIN\u VALUE/base)
将产生一些较大的正值。
result
的法定值将始终小于此值。您希望您的否定案例为
(Integer.MIN\u VALUE/-base)
46340.950001051984^2 = 2.147483647E9
The calculation of 46341.950001051984^2 would overflow.
1.3781057199632372^67 = 2.1474836470000062E9
The calculation of 2.378105719963237^67 would overflow.