go to previous page   go to home page   go to next page highlighting

Answer:

5%3 == 2


Remainder Operator

The remainder() method works the same as the remainder operator % of int.

Recall the rule for %

  1. Perform the operation as if both operands were positive.
  2. If the left operand is negative, the result is negative.
  3. If the left operand is positive, the result is positive.
  4. Ignore the sign of the right operand in all cases.

For example:

17 %  3 == 2     -17 %  3 == -2     
17 % -3 == 2     -17 % -3 == -2

This works for BigIntegers as well.

BigInteger n17 = new BigInteger( "-17" );
BigInteger p3  = new BigInteger( "3" );

System.out.println( n17.remainder( p3 ) );  // prints -2

An ArithmeticException is thrown if the argument of remainder() is zero.

For both int and BigInteger the original integer can be put back together:

quotient * divisor + remainder == theInteger

For example,

-17 / 3 == -5  // quotient  
-17 % 3 == -2  // remainder

(-5) * 3 + (-2) == -15 + (-2) == -17  

Another,

17 / -3 == -5  // quotient  
17 % -3 ==  2  // remainder

(-5) * (-3) + 2 == 15 + 2 == 17  

QUESTION 14:

More Practice! Yay!!

BigInteger p25 = new BigInteger( "25" );
BigInteger n25 = p25.negate();

BigInteger p3 = new BigInteger( "3" );
BigInteger n3 = p3.negate();

BigInteger p5 = new BigInteger( "5" );
Expression ? Result
System.out.println( p25.remainder( p3 ) );
System.out.println( n25.remainder( p3 ) );
System.out.println( p25.remainder( n3 ) );
System.out.println( n25.remainder( n3 ) );
System.out.println( p25.remainder( p5 ) );

Does remainder() sometimes return a zero?


go to previous page   go to home page   go to next page