Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using int, double and long in calculation of powers

I'm having trouble figuring out when to use int, double and long.

I'm working on calculating the power of an integer and return the result as long as the power provided is not a negative number.

For the assignment, I'm required to use the following code to start:

public static long powerN(int number, int power) {

Here's what I came up with:

public class PowerCalculator
{
/**
 * Calculate the non-negative power of an integer number. If a negative power is input, the method returns 1.
 * 
 * @param number The number to take power.
 * @param power The power factor to be taken to.
 * @return The calculation result after taking power of the integer number.
 */
    public static long powerN(int number, int power) {

       if (power > 0)
       {  
         double result = (Math.pow(number, power));  
         return result; 
       }
       else 
       {
         return 1; 
       }
    }
}

I know I'm messing up the use of int, double or long but I don't know how to fix it.

like image 742
MelJ Avatar asked May 01 '15 22:05

MelJ


2 Answers

Wait! If you're doing it yourself, use a faster algorithm like Exponentiation by squaring, something like this:

long powerN(long number, int power){
    long res = 1;
    long sq = number;
    while(power > 0){
        if(power % 2 == 1){
            res *= sq; 
        }
        sq = sq * sq;
        power /= 2;
    }
    return res;
}
like image 67
Julian B. Avatar answered Sep 24 '22 15:09

Julian B.


You could do it by yourself:

public static long powerN(
   int number, 
   int power
) {
   if(power == 0) return 1;
   int result = number;

   while(power > 1) {
      result*=number;
      power--;
   }

   return (long)result;
}

PS: This does not handle negative powers.

like image 43
nramirez Avatar answered Sep 24 '22 15:09

nramirez