MCPcopy Create free account
hub / github.com/chronoxor/FastBinaryEncoding / div

Method div

projects/JavaScript/proto/int64.js:694–775  ·  view source on GitHub ↗

* Divide this value by other one * @this {!Int64} * @param {!Int64|!UInt64|number|string} other Other value * @returns {!Int64} Division of two values

(other)

Source from the content-addressed store, hash-verified

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.

Callers 9

toStringMethod · 0.95
modMethod · 0.95
toStringMethod · 0.45
getMethod · 0.45
setMethod · 0.45
getMethod · 0.45
setMethod · 0.45
big.jsFile · 0.45
test_int64.jsFile · 0.45

Calls 14

eqMethod · 0.95
shrMethod · 0.95
subMethod · 0.95
negMethod · 0.95
isInt64Method · 0.80
isUInt64Method · 0.80
fromValueMethod · 0.45
shlMethod · 0.45
mulMethod · 0.45
addMethod · 0.45
gteMethod · 0.45
toNumberMethod · 0.45

Tested by

no test coverage detected