Skip to content

Instantly share code, notes, and snippets.

@GabrielModog
Last active December 30, 2024 03:49
Show Gist options
  • Save GabrielModog/cd4ef6f7a9d49cd25574ebdfaa62c060 to your computer and use it in GitHub Desktop.
Save GabrielModog/cd4ef6f7a9d49cd25574ebdfaa62c060 to your computer and use it in GitHub Desktop.

Revisions

  1. GabrielModog revised this gist Dec 30, 2024. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions BinaryMath.js
    Original file line number Diff line number Diff line change
    @@ -8,12 +8,12 @@ class BinaryMath {
    }

    static sub(a, b) {
    let carry = (~a) & b
    let barrow = (~a) & b
    b = a ^ b
    carry = carry << 1
    return carry === 0
    barrow = barrow << 1
    return barrow === 0
    ? b
    : this.sum(carry, b)
    : this.sum(barrow, b)
    }

    static mul(a, b) {
  2. GabrielModog created this gist Nov 9, 2024.
    45 changes: 45 additions & 0 deletions BinaryMath.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    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
    }
    }