* Divide this value by other one * @this {!Int64} * @param {!Int64|!UInt64|number|string} other Other value * @returns {!Int64} Division of two values
(other)
| 692 | * @returns {!Int64} Division of two values |
| 693 | */ |
| 694 | div (other) { |
| 695 | if (!Int64.isInt64(other) && !UInt64.isUInt64(other)) { |
| 696 | other = Int64.fromValue(other) |
| 697 | } |
| 698 | if (other.isZero) { |
| 699 | throw new Error('Division by zero!') |
| 700 | } |
| 701 | |
| 702 | if (this.isZero) { |
| 703 | return INT64_ZERO |
| 704 | } |
| 705 | |
| 706 | let approx, rem, res |
| 707 | |
| 708 | // This section is only relevant for signed longs and is derived from the closure library as a whole |
| 709 | if (this.eq(INT64_MIN)) { |
| 710 | // Recall that -MIN_VALUE == MIN_VALUE |
| 711 | if (other.eq(INT64_ONE) || other.eq(INT64_NEG_ONE)) { |
| 712 | return INT64_MIN |
| 713 | } else if (other.eq(INT64_MIN)) { |
| 714 | return INT64_ONE |
| 715 | } else { |
| 716 | // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE| |
| 717 | let halfThis = this.shr(1) |
| 718 | approx = halfThis.div(other).shl(1) |
| 719 | if (approx.eq(INT64_ZERO)) { |
| 720 | return other.isNegative ? INT64_ONE : INT64_NEG_ONE |
| 721 | } else { |
| 722 | rem = this.sub(other.mul(approx)) |
| 723 | res = approx.add(rem.div(other)) |
| 724 | return res |
| 725 | } |
| 726 | } |
| 727 | } else if (other.eq(INT64_MIN)) { |
| 728 | return INT64_ZERO |
| 729 | } |
| 730 | |
| 731 | if (this.isNegative) { |
| 732 | if (other.isNegative) { |
| 733 | return this.neg().div(other.neg()) |
| 734 | } |
| 735 | return this.neg().div(other).neg() |
| 736 | } else if (other.isNegative) { |
| 737 | return this.div(other.neg()).neg() |
| 738 | } |
| 739 | res = INT64_ZERO |
| 740 | |
| 741 | // Repeat the following until the remainder is less than other: find a floating-point that approximates |
| 742 | // remainder / other *from below*, add this into the result, and subtract it from the remainder. |
| 743 | // It is critical that the approximate value is less than or equal to the real value so that the |
| 744 | // remainder never becomes negative. |
| 745 | rem = this |
| 746 | while (rem.gte(other)) { |
| 747 | // Approximate the result of division. This may be a little greater or smaller than the actual value |
| 748 | approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())) |
| 749 | |
| 750 | // We will tweak the approximate result by changing it in the 48-th digit or the smallest non-fractional |
| 751 | // digit, whichever is larger. |
no test coverage detected