在幂计算中使用 int、double 和 long

Using int, double and long in calculation of powers

我无法确定何时使用 int、double 和 long。

我正在计算整数的幂和 return 结果,只要提供的幂不是负数即可。

对于作业,我需要使用以下代码开始:

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

这是我想出的:

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

我知道我搞砸了 int、double 或 long 的使用,但我不知道如何修复它。

你可以自己做:

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: 这不处理负幂。

如果您想使用 Math.pow:

public static long powerN(int number, int power) {
  return (long) Math.pow(number, power);
}

选项 1:将 Math.pow 的结果转换为 long:

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) {

    // write your code after this line
    if (power < 0){
        return 1;
    } else{
        return (long) Math.pow(number, power);
    }

选项 2:不使用 Math.pow

    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) {

    // write your code after this line
    long result = 1;
    while (power > 0) {
        result *= number;
        power--;
    }
    return result;
}

等等!如果你自己做,使用像 Exponentiation by squaring 这样更快的算法,像这样:

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