Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created February 9, 2015 18:51
Show Gist options
  • Save mayfer/c460601ec8a8109ae5b9 to your computer and use it in GitHub Desktop.
Save mayfer/c460601ec8a8109ae5b9 to your computer and use it in GitHub Desktop.
division.rb
# implement division without using multiplication or division operators.
# return the result and the remainder.
# this implementation uses addition for the sum
def divide(number, divisor)
count = 0
sum = 0
while sum <= (number - divisor)
sum += divisor
count += 1
end
result = count
remainder = number - sum
return [result, remainder].inspect
end
# this implementation uses subtraction for the sum, is simpler
def divide(number, divisor)
count = 0
sum = number
while sum >= divisor
sum -= divisor
count += 1
end
result = count
remainder = sum
return [result, remainder]
end
puts divide(10, 3)
puts divide(12, 3)
puts divide(20, 5)
puts divide(342534, 16)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment