Skip to content

Instantly share code, notes, and snippets.

@aks
Created June 30, 2015 07:03
Show Gist options
  • Save aks/add66c6d66f7f9b53145 to your computer and use it in GitHub Desktop.
Save aks/add66c6d66f7f9b53145 to your computer and use it in GitHub Desktop.
division by bitshifting
class Fixnum
def my_div divisor
return nil if divisor == 0
return 0 if self == 0
quotient, mask = 0, 1
dividend = self
while divisor < dividend
divisor <<= 1
mask <<= 1
end
while mask != 0
if dividend >= divisor
dividend -= divisor
quotient += mask
end
divisor >>= 1
mask >>= 1
end
[ quotient, dividend ] # quotient, remainder
end
@aks
Copy link
Author

aks commented Jun 30, 2015

This is a little program to do division by bit-shifting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment