Last active
August 29, 2015 14:23
-
-
Save aks/388eada94f511dfb65e4 to your computer and use it in GitHub Desktop.
no-div.rb
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 ruby | |
# | |
# | |
class FixedNum | |
attr_accessor :num, :rem | |
def initialize num, rem=0 | |
@num = num ; @rem = rem ; self | |
end | |
def inspect | |
@rem == 0 ? @num.to_s : @num.to_s + 'r' + @rem.to_s | |
end | |
def to_s ; self.inspect ; end | |
def ==(v) | |
v.num == @num && v.rem == @rem | |
end | |
end | |
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 | |
FixedNum.new(quotient, dividend) | |
end | |
def real_div divisor | |
return nil if divisor == 0 | |
return 0 if self == 0 | |
q = divisor == 0 ? nil : self / divisor | |
r = divisor == 0 ? nil : self % divisor | |
FixedNum.new(q, r) | |
end | |
end | |
def test_div dividend, divisor | |
test_result = dividend.my_div divisor | |
ref_result = dividend.real_div divisor | |
if test_result != ref_result | |
puts "#{dividend} / #{divisor} => #{test_result} not #{ref_result}" | |
end | |
end | |
1000.times do |x| | |
dividend = rand(100000) | |
divisor = rand(100000) | |
test_div dividend, divisor | |
end | |
exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a complete program that demonstrates that the bitshifting division is exactly the same as "real" division.
The test program runs a thousand random integers as both dividends and divisors, and compares the bit-shifting division versus the built-in division.
No output means no errors.