Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Created September 8, 2020 19:59
Show Gist options
  • Save davepkennedy/f3c1da95731512c52556ca1a32137132 to your computer and use it in GitHub Desktop.
Save davepkennedy/f3c1da95731512c52556ca1a32137132 to your computer and use it in GitHub Desktop.
Find a quotient and a remainder without using division or modulo
# Quotient and Remainder without using division
def divide (num, div):
low, high = 0, num
d = high - low
# Keep going until there's no more midpoints between high and low
# Need to find the value for x such that x*div ~ num
while d > 1:
# Calculate d here or there's one iteration too few
d = high - low
# Rshift kinda sorta halves the number
# Enough to find a midpoint
mid = low+(d>>1)
# Is the midpoint*div higher than the num?
# If so, x is between low and mid
# Otherwise x is between mid and high
if mid*div > num:
high = mid
else:
low = mid
return mid, num-mid*div
# Should print (3, 2)
# 3*3 == 9
# 11-9 = 2
print (divide (11,3))
@davepkennedy
Copy link
Author

Basically a search for a number in a dataset - but what are we searching for?
Looking for a number n such that n*div is very close to num. Find the n that produces a number the closest to num without exceeding it and that's your answer

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