// Subtraction char* Sub(char* s1, char* s2, char* result) { BigInt a, b, c; StrToBigInt(s1, &a); StrToBigInt(s2, &b); DoSub(&a, &b, &c); return BigIntToStr(&c, result); }
double DoOperation(char operation, double op1, double op2, int* isErr) { switch (operation) { case '+': return DoAdd(op1, op2); break; case '-': return DoSub(op1, op2); break; case '*': return DoMul(op1, op2); break; case '/': return DoDiv(op1, op2, isErr); break; } return op2; //return WinCalculator->DoOperation(operation, op1, op2, isErr); }
// implement of division by using binary search // result = a / b BigInt* DoDiv(BigInt* a, BigInt* b, BigInt* result, BigInt* remainder) { int low, high, mid; BigInt c, d, e, t; low = 0; // the min of left shift high = GetMaxLeftShiftLen(b); // the max of left shift memset(t.bit, 0, BIG_INT_BIT_LEN); // init 0 CopyBigInt(a, &c); // c = a // if a sign == b sign, do subtraction if (a->bit[SIGN_BIT] == b->bit[SIGN_BIT]) { t.bit[SIGN_BIT] = POSITIVE; while (1) { while (low <= high) { mid = (low + high) / 2; ShiftArithmeticLeft(b, mid, &d); DoSub(&c, &d, &e); // e = c - d // e >= 0 if (d.bit[SIGN_BIT] == e.bit[SIGN_BIT] || IsZero(&e)) low = mid + 1; else high = mid - 1; } // high == -1 means c - b < 0 if (high != -1) { t.bit[high] = 1; // here unified the operation // it can improve i think ShiftArithmeticLeft(b, high, &d); // c = c - d, let c be the next dividend DoSub(&c, &d, &c); low = 0; high--; } else { // now the dividend c is the remainder CopyBigInt(&c, remainder); break; } } } // if a sign != b sign, do addition else { t.bit[SIGN_BIT] = NEGATIVE; while (1) { while (low <= high) { mid = (low + high) / 2; ShiftArithmeticLeft(b, mid, &d); DoAdd(&c, &d, &e); // e = c + d // e >= 0 if (d.bit[SIGN_BIT] != e.bit[SIGN_BIT] || IsZero(&e)) low = mid + 1; else high = mid - 1; } // high == -1 means c - b < 0 if (high != -1) { t.bit[high] = 1; // here unified the operation // it can improve i think ShiftArithmeticLeft(b, high, &d); // c = c + d, let c be the next dividend DoAdd(&c, &d, &c); low = 0; high--; } else { // now the dividend c is the remainder CopyBigInt(&c, remainder); break; } } } return ToComplement(&t, result); }