java.math.BigInteger mod(BigInteger m)

Description

On this document we will be showing a java example on how to use the mod() method of BigInteger Class. Basically this method performs the modulo operator between this BigInteger and method argument m or simply this % m. This is similar in nature with the remainder() method of BigInteger class however in using the remainder, negative results will be returned. Meanwhile in using the mod() operator it will always return a positive value.

Notes:

  • ArithmeticException will be thrown if the modulo is less than or equal to zero.

Method Syntax

public BigInteger mod(BigInteger m)

Method Argument

Data Type Parameter Description
BigInteger m the modulus

Method Returns

The mod(BigInteger m) method returns a BigInteger whose value is (this mod m). This method differs from remainder in that it always returns a non-negative BigInteger.

Compatibility

Requires Java 1.1 and up

Java BigInteger mod(BigInteger m) Example

Below is a java code demonstrates the use of mod(BigInteger m) method of BigInteger class. The example presented might be simple however it shows the behavior of the mod(BigInteger m) method.

package com.javatutorialhq.java.examples;

import java.math.BigInteger;
import java.util.Scanner;

/*
 * A java example source code to demonstrate
 * the use of mod() method of BigInteger class
 */

public class BigIntegerModExample {

	public static void main(String[] args) {	
		
		// ask for two input
		System.out.print("Enter a number:");
		Scanner s = new Scanner(System.in);
		String firstInput = s.nextLine();
		System.out.print("Enter the divisor:");
		String secondInput = s.nextLine();
		s.close();
		
		// convert the string input to BigInteger
		BigInteger value = new BigInteger(firstInput);
		BigInteger modulo = new BigInteger(secondInput);
		
		// get the modulo value between the two BigInteger
		BigInteger result = value.mod(modulo);
		System.out.println("The result is "+result);
		
		
				
	}

}

This example is a lot simpler than it looks. We simply ask the user for two inputs and convert these into BigInteger. We then get the result of the mod() method of the first input and the second input.

Sample Output

Below is the sample output when you run the above example.

BigInteger mod() example output