Guava IntMath類


IntMath提供整型的實用方法。

類宣告

以下是com.google.common.math.IntMath類的宣告:

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

方法

S.N. 方法及說明
1 static int binomial(int n, int k)
返回n個選擇K,也被稱為n和k,或Integer.MAX_VALUE的二項式係數,如果結果在一個int不適合
2 static int checkedAdd(int a, int b)
返回a和b的總和,只要它不會溢位。
3 static int checkedMultiply(int a, int b)
返回a和b的產物,只要它不會溢位。
4 static int checkedPow(int b, int k)
返回b的第k冪,只要它不會溢位。
5 static int checkedSubtract(int a, int b)
返回a和b的差,只要它不會溢位。
6 static int divide(int p, int q, RoundingMode mode)
返回除以p由q,使用指定RoundingMode的四捨五入結果。
7 static int factorial(int n)
返回n個!,也就是說,前n個正整數的乘積,如果n==0則返回1,或者是Integer.MAX_VALUE如果結果不適合在一個int值。
8 static int gcd(int a, int b)
返回a, b的最大公約數。
9 static boolean isPowerOfTwo(int x)
返回true,如果x代表兩個冪。
10 static int log10(int x, RoundingMode mode)
返回基數為10的對數x,根據指定的舍入模式圓形。
11 static int log2(int x, RoundingMode mode)
返回基數為2-對數x,根據指定的舍入模式圓形。
12 static int mean(int x, int y)
返回x和y的算術平均值,取整。
13 static int mod(int x, int m)
返回x模m,一個非負的值小於m以下。
14 static int pow(int b, int k)
返回b的第k冪。
15 static 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: overflow
20
Error: mode was UNNECESSARY, but rounding was necessary
Log2(2): 1
Log10(10): 1
sqrt(100): 10
gcd(100,50): 50
modulus(100,50): 0
factorial(5): 120