Skip to content

Instantly share code, notes, and snippets.

@GabrielModog
Last active December 30, 2024 03:49
Show Gist options
  • Select an option

  • Save GabrielModog/cd4ef6f7a9d49cd25574ebdfaa62c060 to your computer and use it in GitHub Desktop.

Select an option

Save GabrielModog/cd4ef6f7a9d49cd25574ebdfaa62c060 to your computer and use it in GitHub Desktop.
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