当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java LongMath.checkedPow(long b, int k)用法及代码示例


CheckedPow(long b,long k)是Guava LongMath类的一种方法,该方法接受两个参数b和k,并用于查找b的k-th幂。

用法:

public static long checkedPow(long b, long k)

参数:该方法接受两个参数b和k。参数b称为基数,它升为k-th的幂。


返回值:此方法返回b的k-th幂。

异常:如果b的k-th的幂在有符号长算法中溢出,则checkedPow(long b,long k)方法将引发ArithmeticException。

以下示例说明了上述方法的实现:

范例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-



相关用法


注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Java Guava | LongMath.checkedPow(long b, int k) method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。