Created
June 30, 2015 07:03
-
-
Save aks/add66c6d66f7f9b53145 to your computer and use it in GitHub Desktop.
division by bitshifting
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a little program to do division by bit-shifting.