當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Guava LongMath mod(long x, long m)用法及代碼示例


Guava LongMath類的mod(long x,long m)方法接受兩個參數x和m,並用於計算m下的x模量值。

用法:

public static long mod(long x, long m)

參數:此方法接受兩個參數x和m,它們是長類型的,用於計算x模m。


返回值:該方法返回x mod m,該值將是小於m的非負值。

異常:如果m <= 0,則方法mod(long x,long m)引發ArithmeticException。

以下示例說明了mod(long x,long m)方法:

範例1:

// Java code to show implementation of 
// mod(long x, long m) 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 x1 = -77; 
        long m1 = 4; 
  
        long ans1 = LongMath.mod(x1, m1); 
  
        // Using mod(long x, long m) 
        // method of Guava's LongMath class 
        System.out.println(x1 + " mod "
                           + m1 + " is:" + ans1); 
  
        long x2 = 22; 
        long m2 = 6; 
  
        long ans2 = LongMath.mod(x2, m2); 
  
        // Using mod(long x, long m) 
        // method of Guava's LongMath class 
        System.out.println(x2 + " mod "
                           + m2 + " is:" + ans2); 
    } 
}
輸出:
-77 mod 4 is:3
22 mod 6 is:4

範例2:

// Java code to show implementation of 
// mod(long x, long m) method of Guava's 
// LongMath class 
import java.math.RoundingMode; 
import com.google.common.math.LongMath; 
  
class GFG { 
  
    static long findMod(long x, long m) 
    { 
        try { 
            // Using mod(long x, long m) 
            // method of Guava's LongMath class 
            // This should throw "ArithmeticException" 
            // as m <= 0 
            long ans = LongMath.mod(x, m); 
  
            // Return the answer 
            return ans; 
        } 
        catch (Exception e) { 
            System.out.println(e); 
            return -1; 
        } 
    } 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        long x = 11; 
        long m = -5; 
  
        try { 
            // Function calling 
            findMod(x, m); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
java.lang.ArithmeticException:Modulus must be positive

參考: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/LongMath.html#mod-long-int-



相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Java Guava | mod(long x, long m) of LongMath Class with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。