Guava – LongMath.checkedPow方法与实例

Guava – LongMath.checkedPow方法与实例

checkedPow(long b, long k)是Guava的LongMath类的一个方法,它接受两个参数bk,用来寻找b的k次方.

语法:

public static long checkedPow(long b, long k)

参数: 该方法接受两个参数,b和k。参数b被称为base,它被提高到k次方.

返回值: 该方法返回b的k次方.

异常: 如果b的k次方在有符号长运算中溢出,方法checkedPow(long b, long k)会抛出算术异常.

下面的例子说明了上述方法的实施情况:

示例1:

// Java code to show implementation of
// checkedPow(long b, long 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 = 5;
        int k1 = 7;
  
        // Using checkedPow(long b, long k) method
        // of Guava's LongMath class
        long ans1 = LongMath.checkedPow(b1, k1);
  
        System.out.println(b1 + " to the "
                           + k1 + "th power is: "
                           + ans1);
  
        long b2 = 19;
        int k2 = 4;
  
        // Using checkedPow(long b, long k) method
        // of Guava's LongMath class
        long ans2 = LongMath.checkedPow(b2, k2);
  
        System.out.println(b2 + " to the " + k2
                           + "th power is: "
                           + ans2);
    }
}

输出:

5 to the 7th power is: 78125
19 to the 4th power is: 130321

示例2:

// Java code to show implementation of
// checkedPow(long b, long 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 checkedPow(long b, long k) method of
            // Guava's LongMath class
            // This should raise "ArithmeticException" as
            // b to the kth power overflows in
            // signed long arithmetic
            long ans = LongMath.checkedPow(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 = 20;
        int k = 25;
  
        try {
  
            // Function calling
            findPow(b, k);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

java.lang.ArithmeticException: overflow

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程