Guava IntMath 类

来源:这里教程网 时间:2026-02-17 21:39:12 作者:

Guava IntMath 类

IntMath 提供了一些 int 的实用方法。

类声明

以下是 com.google.common.math.IntMath 类的声明:

@GwtCompatible(emulated = true)public final class IntMath   extends Object

方法

序号方法与描述
1static int binomial(int n, int k) 返回组合数 n choose k,也称为 n 和 k 的二项式系数,如果结果不适合 int,则返回 Integer.MAX_VALUE。
2static int checkedAdd(int a, int b) 返回 a 和 b 的和,前提是它们不会溢出。
3static int checkedMultiply(int a, int b) 返回 a 和 b 的乘积,前提是它们不会溢出。
4static int checkedPow(int b, int k) 返回 b 的 k 次方,前提是它不会溢出。
5static int checkedSubtract(int a, int b) 返回a和b的差,前提是不会溢出。
6static int divide(int p, int q, RoundingMode mode) 返回使用指定的RoundingMode四舍五入后p除以q的结果。
7static int factorial(int n) 返回n!,即前n个正整数的乘积,如果n == 0,则返回1,如果结果不适合int类型,则返回Integer.MAX_VALUE。
8static int gcd(int a, int b) 返回a和b的最大公约数。
9static boolean isPowerOfTwo(int x) 如果x表示2的幂次方,则返回true。
10static int log10(int x, RoundingMode mode) 返回x的以10为底的对数,根据指定的舍入模式进行四舍五入。
11static int log2(int x, RoundingMode mode) 返回x的以2为底的对数,根据指定的舍入模式进行四舍五入。
12static int mean(int x, int y) 返回x和y的算术平均值,向负无穷方向舍入。
13static int mod(int x, int m) 返回x对m取模的非负值,小于m。
14static int pow(int b, int k) 返回b的k次方。
15static int sqrt(int x, RoundingMode mode) 返回x的平方根,四舍五入方式为指定的四舍五入模式。

继承的方法

该类继承了以下类的方法:

java.lang.Object

IntMath类的示例

使用您选择的任何编辑器,创建以下Java程序,例如在 C:/ > Guava中。

GuavaTester.java

import java.math.RoundingMode;import com.google.common.math.IntMath;public class GuavaTester {   public static void main(String args[]) {      GuavaTester tester = new GuavaTester();      tester.testIntMath();   }   private void testIntMath() {      try {         System.out.println(IntMath.checkedAdd(Integer.MAX_VALUE, Integer.MAX_VALUE));      } catch(ArithmeticException e) {         System.out.println("Error: " + e.getMessage());      }      System.out.println(IntMath.divide(100, 5, RoundingMode.UNNECESSARY));      try {         //exception will be thrown as 100 is not completely divisible by 3         // thus rounding is required, and RoundingMode is set as UNNESSARY         System.out.println(IntMath.divide(100, 3, RoundingMode.UNNECESSARY));      } catch(ArithmeticException e) {         System.out.println("Error: " + e.getMessage());      }      System.out.println("Log2(2): " + IntMath.log2(2, RoundingMode.HALF_EVEN));      System.out.println("Log10(10): " + IntMath.log10(10, RoundingMode.HALF_EVEN));      System.out.println("sqrt(100): " + IntMath.sqrt(IntMath.pow(10,2), RoundingMode.HALF_EVEN));      System.out.println("gcd(100,50): " + IntMath.gcd(100,50));      System.out.println("modulus(100,50): " + IntMath.mod(100,50));      System.out.println("factorial(5): " + IntMath.factorial(5));   }}

验证结果

按如下方式使用 javac 编译器编译该类:

C:\Guava>javac GuavaTester.java

现在运行GuavaTester看结果。

C:\Guava>java GuavaTester

查看结果。

Error: overflow20Error: mode was UNNECESSARY, but rounding was necessaryLog2(2): 1Log10(10): 1sqrt(100): 10gcd(100,50): 50modulus(100,50): 0factorial(5): 120

相关推荐