The mod(long x, long m) method of Guava’s LongMath Class accepts two parameters x and m, and used to calculate the value of x modulus under m.
Syntax:
public static long mod(long x, long m)
Parameters: This method accepts two parameters x and m which are of long type to calculate x modulo m.
Return Value: The method returns x mod m that will be a non-negative value less than m.
Exception: The method mod(long x, long m) throws ArithmeticException if m <= 0.
Below examples illustrate the mod(long x, long m) method:
Example 1 :
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
public static void main(String args[])
{
long x1 = - 77 ;
long m1 = 4 ;
long ans1 = LongMath.mod(x1, m1);
System.out.println(x1 + " mod "
+ m1 + " is : " + ans1);
long x2 = 22 ;
long m2 = 6 ;
long ans2 = LongMath.mod(x2, m2);
System.out.println(x2 + " mod "
+ m2 + " is : " + ans2);
}
}
|
Output:
-77 mod 4 is : 3
22 mod 6 is : 4
Example 2:
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
static long findMod( long x, long m)
{
try {
long ans = LongMath.mod(x, m);
return ans;
}
catch (Exception e) {
System.out.println(e);
return - 1 ;
}
}
public static void main(String args[])
{
long x = 11 ;
long m = - 5 ;
try {
findMod(x, m);
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
java.lang.ArithmeticException: Modulus must be positive
Reference: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/LongMath.html#mod-long-int-