Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created February 9, 2015 18:51
Show Gist options
  • Save mayfer/e4815fd82a5078622c09 to your computer and use it in GitHub Desktop.
Save mayfer/e4815fd82a5078622c09 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