Guava LongMath類

LongMath提供long基礎類型的實用方法。

類聲明

以下是com.google.common.math.LongMath類的聲明:

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

方法

S.N.

方法及說明

1

static long binomial(int n, int k)
返回n個選擇K,也稱爲n和k,或爲Long.MAX_VALUE的二項式係數,如果long結果不相符。

1

static long checkedAdd(long a, long b)
返回a和b的總和,只要它不會溢出。

2

static long checkedMultiply(long a, long b)
返回a和b的產物,只要它不會溢出。

3

static long checkedPow(long b, int k)
返回b的第k冪,只要它不會溢出。

4

static long checkedSubtract(long a, long b)
返回a和b的差,只要它不會溢出。

5

static long divide(long p, long q, RoundingMode mode)
返回除以p由q,使用指定的RoundingMode四捨五入的結果。

6

static long factorial(int n)
返回n!,也就是說,前n個正整數的乘積,如果n==則返回1,或爲Long.MAX_VALUE如果結果long不相符。

7

static long gcd(long a, long b)
返回a, b的最大公約數。

8

static boolean isPowerOfTwo(long x)
返回true,如果x代表兩個冪。

9

static int log10(long x, RoundingMode mode)
返回基數爲10的對數x,根據指定的舍入模式圓形。

10

static int log2(long x, RoundingMode mode)
返回基數爲2-對數x,根據指定的舍入模式圓形。

11

static long mean(long x, long y)
返回x和y的算術平均值,四捨五入向負無窮大。

12

static int mod(long x, int m)
返回x模m,一個非負的值小於m以下。

13

static long mod(long x, long m)
返回x模m,一個非負的值小於m以下。

14

static long pow(long b, int k)
返回b爲第k冪。

15

static long sqrt(long x, RoundingMode mode)
返回x的平方根,大概指定的舍入模式。

方法繼承

這個類繼承了以下類方法:

  • java.lang.Object

LongMath 示例

使用所選擇的任何編輯器創建下面的java程序 C:/> Guava

GuavaTester.java

import java.math.RoundingMode; import com.google.common.math.LongMath; public class GuavaTester { public static void main(String args[]){ GuavaTester tester = new GuavaTester(); tester.testLongMath(); } private void testLongMath(){ try{ System.out.println(LongMath.checkedAdd(Long.MAX_VALUE, Long.MAX_VALUE)); }catch(ArithmeticException e){ System.out.println("Error: " + e.getMessage()); } System.out.println(LongMath.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(LongMath.divide(100, 3, RoundingMode.UNNECESSARY)); }catch(ArithmeticException e){ System.out.println("Error: " + e.getMessage()); } System.out.println("Log2(2): "+LongMath.log2(2, RoundingMode.HALF_EVEN)); System.out.println("Log10(10): "+LongMath.log10(10, RoundingMode.HALF_EVEN)); System.out.println("sqrt(100): "+LongMath.sqrt(LongMath.pow(10,2), RoundingMode.HALF_EVEN)); System.out.println("gcd(100,50): "+LongMath.gcd(100,50)); System.out.println("modulus(100,50): "+LongMath.mod(100,50)); System.out.println("factorial(5): "+LongMath.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