Длинное деление Java без / оператора, имеющего проблему с частным, остаток - PullRequest
1 голос
/ 26 октября 2019

Я написал метод деления, который делает длинное деление без / оператора, но когда я запускаю юнит-тест, он дает мне правильный коэффициент, но неправильный остаток.

Это мой метод деления:

public MyBigInteger dividedBy(MyBigInteger divisor) throws Exception {

    int x = 0;
    int temp = 0;
    int count = 0;
    int y = 10;
    int total = 0;
    int total2 = 0;

    reverse(coefficients);
    reverse(divisor.coefficients);

    int current = 1;
    int quotient = 0;

    for (Integer i : coefficients) {
        total = 10 * total + i;
    }

    for (Integer j : divisor.coefficients) {
        total2 = 10 * total2 + j;
    }

    if (total2 > total) {
        throw new Exception("The answer is 0");
    }
    if (total2 == total) {
        throw new Exception("The answer is 1");
    }

    while (total2 <= total) {
        total2 <<= 1;
        current <<= 1;
    }

    total2 >>= 1;
    current >>= 1;

    while (current != 0) {
        if (total >= total2) {
            total -= total2;
            quotient |= current;
        }

        current >>= 1;
        total2 >>= 1;
    }
    MyBigInteger answer = new MyBigInteger(quotient, this.base);
    return answer;
}

А это тест-код:

quo = big1.divide(big2).toString(base);
quo = "(" + quo + ")_" + base;
System.out.print("divide: big1/big2     = "); // BigInteger
System.out.println(quo);

long s_time = System.currentTimeMillis();
System.out.print("divide: n1/n2         = "); // MyBigInteger
try {
    quo_mybig = n1.dividedBy(n2).toString();
    System.out.println(quo_mybig);
    System.out.println("Time Required (Divide): " + (System.currentTimeMillis() - s_time) + " ms");
    System.out.println(remarks);
    if (quo.contentEquals(quo_mybig))
        System.out.println("Test passed.");
    else
        System.out.println("Test failed.");
}

И это то, что я получил

big1: (3956)_10     (BigInteger)

big2: (27)_10      (BigInteger)


n1: (3956)_10     (MyBigInteger)

n2: (27)_10      (MyBigInteger)


divide: big1/big2     = (146)_10

divide: n1/n2         = (146)_10

Time Required (Divide): 0 ms

Remarks: An efficent implementation finds a solution within 1 ms. 

Test passed.

big1 mod big2 = (14)_10

n1 mod n2 = (1499)_10

Test failed.

Когда я ставлю MyBigInteger answer = new MyBigInteger(146,this.base); вместо MyBigInteger answer = new MyBigInteger(quotient,this.base);, я получаютест мод прошел, хотя частное 146 (проверено с помощью system.out.println)

Я понятия не имею, что здесь не так. Пожалуйста, помогите ...

...