Java中的 BigInteger mod() 方法
Java.math.BigInteger.mod(BigInteger big)方法返回一个BigInteger,它的值等于(this BigInteger modfunction big(BigInteger pass as parameter))。换句话说,我们可以说这个方法在执行后返回值(this % big) step.mod 操作找到这个 BigInteger 除以另一个作为参数传递的 BigInteger 后的余数。
Java.math.BigInteger.mod(BigInteger big) 和Java.math.BigInteger.remainder(BigInteger val) 两个函数都找到余数,但 mod 操作总是返回非负 BigInteger。
句法:
public BigInteger mod(BigInteger big)
参数:该函数接受一个强制参数big ,它指定了我们想要分割这个 bigInteger 对象的 BigInteger 对象。
返回值:该方法返回与此 BigInteger mod big 相等的 BigInteger(BigInteger 作为参数传递)。
异常:该方法在big ≤ 0时抛出ArithmeticException
例子:
Input: BigInteger1=321456, BigInteger2=31711
Output: 4346
Explanation: BigInteger1.mod(BigInteger2)=4346. The divide operation between
321456 and 31711 returns 4346 as remainder.
Input: BigInteger1=59185482345, BigInteger2=59185482345
Output: 0
Explanation: BigInteger1.mod(BigInteger2)=0. The divide operation between
59185482345 and 59185482345 returns 0 as remainder.
下面的程序说明了 BigInteger 类的 mod() 方法:
示例 1:
// Java program to demonstrate mod() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// Creating 2 BigInteger objects
BigInteger b1, b2;
b1 = new BigInteger("321456");
b2 = new BigInteger("31711");
// apply mod() method
BigInteger result = b1.mod(b2);
// print result
System.out.println("Result of mod
operation between " + b1
+ " and " + b2 +
" equal to " + result);
}
}
Result of mod operation between 321456 and 31711 equal to 4346
示例 2:当两者的价值相等时。
// Java program to demonstrate mod() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// Creating 2 BigInteger objects
BigInteger b1, b2;
b1 = new BigInteger("3515219485");
b2 = new BigInteger("3515219485");
// apply mod() method
BigInteger result = b1.mod(b2);
// print result
System.out.println("Result of mod
operation between " + b1
+ " and " + b2 +
" equal to " + result);
}
}
Result of mod operation between 3515219485 and 3515219485 equal to 0
示例 3:当作为参数传递的 BigInteger 小于零时,程序显示异常。
// Java program to demonstrate mod() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// Creating 2 BigInteger objects
BigInteger b1, b2;
b1 = new BigInteger("3515219485");
b2 = new BigInteger("-1711");
// apply mod() method
BigInteger result = b1.mod(b2);
// print result
System.out.println("Result of mod
operation between " + b1
+ " and " + b2 +
" equal to " + result);
}
}
输出:
Exception in thread "main" java.lang.ArithmeticException: BigInteger: modulus not positive
at java.math.BigInteger.mod(BigInteger.java:2458)
at GFG.main(GFG.java:17)
参考: https: Java Java)