Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to write method that return power of only integer numbers

Tags:

java

I need to write a method in java to return the power of only integer number and i want this method to return -1 or fire exception if the number exceeds the Integer.MAX_VALUE:

I tried the first and easy step:

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;
}

Is the above method accurate, as after debugging i found that when the result exceeds the Integer.MAX_VALUE it will go to negative number, or there is another way to handle this?

like image 561
Marzouk Avatar asked Jun 19 '15 14:06

Marzouk


People also ask

How do you calculate the power of a number whether a number is power of 10?

A power of 10 is as many number 10s as indicated by the exponent multiplied together. Thus, shown in long form, a power of 10 is the number 1 followed by n zeros, where n is the exponent and is greater than 0; for example, 106 is written 1,000,000.

How do you check if a number is power of any number?

Following are detailed step. 1) Initialize pow = x, i = 1 2) while (pow < y) { pow = pow*pow i *= 2 } 3) If pow == y return true; 4) Else construct an array of powers from x^i to x^(i/2) 5) Binary Search for y in array constructed in step 4. If not found, return false. Else return true.


1 Answers

Your method will work if the base can only be positive integer. Underflow might occur your base is a negative integer and your power is an odd number.

An easy but not optimal way to handle this situation is to use long data type to store the output and compare the output to check whether it is between Integer.MAX_VALUE and Integer.MIN_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 || result < Integer.MIN_VALUE) {
        return -1;
    }
 }
 return result;
}
like image 184
PythaLye Avatar answered Nov 15 '22 08:11

PythaLye