Last active
December 30, 2024 03:49
-
-
Save GabrielModog/cd4ef6f7a9d49cd25574ebdfaa62c060 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class BinaryMath { | |
| static sum(a, b) { | |
| let carry = (a & b) | |
| carry = carry << 1 | |
| return carry === 0 | |
| ? b | |
| : this.sum(carry, b) | |
| } | |
| static sub(a, b) { | |
| let carry = (~a) & b | |
| b = a ^ b | |
| carry = carry << 1 | |
| return carry === 0 | |
| ? b | |
| : this.sum(carry, b) | |
| } | |
| static mul(a, b) { | |
| let carry = 0 | |
| while(b > 0) { | |
| if(b & 1) { | |
| carry = this.sum(carry, a) | |
| } | |
| a <<= 1 | |
| b >>= 1 | |
| } | |
| return carry | |
| } | |
| static div(a, b) { | |
| let quotient = 0 | |
| let remainder = a | |
| while(remainder >= b) { | |
| let shift = 0 | |
| while(remainder >= (b << shift)) { | |
| shift++ | |
| } | |
| shift-- | |
| quotient |= (1 << shift) | |
| remainder = this.subtract(remainder, b << shift) | |
| } | |
| return quotient | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment