JDK-8334483 : MutableBigInteger's methods compare and compareShifted are broken
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.math
  • Affected Version: 22.0.1
  • Priority: P4
  • Status: Resolved
  • Resolution: Not an Issue
  • OS: generic
  • CPU: generic
  • Submitted: 2024-06-15
  • Updated: 2024-06-18
  • Resolved: 2024-06-18
Description
ADDITIONAL SYSTEM INFORMATION :
JDK 22.0.1

A DESCRIPTION OF THE PROBLEM :
The methods compare and compareShifted implicitly assume that the operands have no leading zeros, but the the method compare is invoked by subtract, in which there isn't this assuption. Indeed, this leaded to several failures in an algorithm I was trying to implement for square root of MutableBigIntegers.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
MutableBigInteger a = new MutableBigInteger(new int[] { 0, 0 });
MutableBigInteger b = new MutableBigInteger(new int[] { 1 });
int comp = a.compare(b);

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
comp == -1
ACTUAL -
comp == 1

---------- BEGIN SOURCE ----------
To execute this code, you must place this method in package java.math:

public static void main(String[] args) {
        MutableBigInteger a = new MutableBigInteger(new int[] { 0, 0 });
        MutableBigInteger b = new MutableBigInteger(new int[] { 1 });
        
        if (a.compare(b) != a.toBigInteger().compareTo(b.toBigInteger()))
            System.out.println("comparison failure");
}
---------- END SOURCE ----------

FREQUENCY : occasionally



Comments
Information received from Submitter ================================ This code must be placed in a class that is in the same package of MutableBigInteger because this class is not visible outside the package. I noticed the bug because I was implementing an algorithm for MutableBigInteger that uses the method subtract, which invokes the method compare. I resolved this bug by invoking the normalize() on the argument in the method compare before beginning the comparison.
18-06-2024

Mail to Submitter =============== This is regarding the JBS bug reported on ‘MutableBigInteger's methods compare and compareShifted are broken’ In the reproducer code submitted, you mentioned placing the main method in the package java.math. Can you provide the exact steps on how it is done so that we can try to replicate it? This would help us understand the issue and provide a fix if needed.
18-06-2024