Created
August 2, 2012 10:45
-
-
Save gustavoatt/3236201 to your computer and use it in GitHub Desktop.
Division without arithmetic operators
This file contains 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
#!/usr/bin/env python | |
def slow_divide(x, y): | |
res = 0 | |
while x >= y: | |
x = x - y | |
res += 1 | |
return res | |
def divide(x, y): | |
# Based on the fact that x/y = (n*y + x - n*y) /y = n + (x - n*y)/y | |
# where n can be anything. In particular n = 2^i | |
if x <= (y << 1): | |
return slow_divide(x, y) | |
quotient = 1 | |
factor = y | |
while factor <= x: | |
factor = factor << 1 | |
quotient = quotient << 1 | |
# factor is bigger than x now, so go back once | |
factor = factor >> 1 | |
quotient = quotient >> 1 | |
return quotient + slow_divide(x - factor, y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment