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


Java Guava 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称为基数,它升为k-th的幂。


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

异常:如果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-



相关用法


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