def binaryDivision(int a, int b) {
    int result = 0
    int sign = 0
    if (a < 0) {
        sign = sign + 1
        a = 0 - a
    }
    if (b < 0) {
        sign = sign - 1
        b = 0 - b
    }
    
    int limit = a >> 1
    if (limit < (1 << 30)) limit = 1 << 30
    int origB = b
    while (b < limit) {
        b = b << 1
    }
    while (b >= origB) {
        result = result << 1
        if (a >= b) {
            a = a - b
            result = result + 1
        }
        b = b >> 1
    }
    
    if (sign != 0) result = 0 - result
    return result
}

100000.times {
    def RNG = new Random()
    int a = RNG.nextInt()
    int b = RNG.nextInt()
    int expected = a/b
    //println "$a $b"
    assert binaryDivision(a, b) == expected
}

int divBy10(int x) {
    int result = 214748364
    for (int i = 32; i > 0; i = i - 1) {
        if (x & 1) {
            //Integer.parseInt('00011001100110011001100110011001', 2)
            result = result + 429496729
        }
        x = x >> 1
        result = result >> 1
    }
    return result
}

100000.times {
    assert divBy10(it) == (it / 10 as int)
}
