Guava – LongMath.pow方法与实例

Guava – LongMath.pow方法与实例

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程