Skip to content

Instantly share code, notes, and snippets.

@gustavoatt
Created August 2, 2012 10:45
Show Gist options
  • Save gustavoatt/3236201 to your computer and use it in GitHub Desktop.
Save gustavoatt/3236201 to your computer and use it in GitHub Desktop.
Division without arithmetic operators
#!/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