📌  相关文章
📜  Java番石榴 |带示例的 LongMath 类的 pow(long b, int k)

📅  最后修改于: 2022-05-13 01:55:04.033000             🧑  作者: Mango

Java番石榴 |带示例的 LongMath 类的 pow(long b, int k)

Guava 的 LongMath 类的方法pow(long b, int k)返回b 的 k 次方。即使结果溢出,也会等于 BigInteger.valueOf(b).pow(k).longValue()。此实现在O(log k)时间内运行。

句法:

public static long pow(long b, int k)

参数:该方法接受两个参数,b 和 k。参数 b 称为base的 k 次方。

返回值:此方法返回 b 的 k 次方。

异常:如果 k 为负数,此方法将引发IllegalArgumentException

示例 1:

// Java code to show implementation of
// pow(long b, int k) method of Guava's
// LongMath Class
  
import java.math.RoundingMode;
import com.google.common.math.LongMath;
  
class GFG {
  
    // Driver code
    public static void main(String args[])
    {
        long b1 = 4;
        int k1 = 5;
  
        long ans1 = LongMath.pow(b1, k1);
  
        System.out.println(b1 + " to the " + k1
                           + "th power is: "
                           + ans1);
  
        long b2 = 12;
        int k2 = 3;
  
        long ans2 = LongMath.pow(b2, k2);
  
        System.out.println(b2 + " to the " + k2
                           + "rd power is: "
                           + ans2);
    }
}
输出:
4 to the 5th power is: 1024
12 to the 3rd power is: 1728

示例 2:

// Java code to show implementation of
// pow(long b, int k) method of Guava's
// LongMath class
  
import java.math.RoundingMode;
import com.google.common.math.LongMath;
  
class GFG {
  
    static long findPow(long b, int k)
    {
        try {
            // Using pow(long b, int k)
            // method of Guava's LongMath class
            // This should throw "IllegalArgumentException"
            // as k < 0
            long ans = LongMath.pow(b, k);
  
            // Return the answer
            return ans;
        }
        catch (Exception e) {
            System.out.println(e);
            return -1;
        }
    }
  
    // Driver code
    public static void main(String args[])
    {
        long b = 4;
        int k = -5;
  
        try {
            // Using pow(long b, int k)
            // method of Guava's LongMath class
            // This should throw "IllegalArgumentException"
            // as k < 0
            LongMath.pow(b, k);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
java.lang.IllegalArgumentException: exponent (-5) must be >= 0

参考: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/LongMath.html#pow-long-int-