没有/运算符的Java长除法存在商,余数问题

时间:2019-10-26 19:15:55

标签: java biginteger

我编写了一个除法方法,该方法无需/运算符即可进行长除法,但是当我运行单元测试时,它为我提供了正确的商,但余数错误。

这是我的除法:

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检查),我仍然通过了mod测试

我不知道这里出了什么问题。请帮助...

0 个答案:

没有答案