Created
August 18, 2021 17:37
-
-
Save HalCanary/a2602d9f025e80d2d670e42ce5d274dd to your computer and use it in GitHub Desktop.
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
from __future__ import division | |
def division(n, d): | |
''' | |
find integers q, r such that | |
d * q + r = n | |
0 <= r < d | |
''' | |
assert n >= 0 | |
assert d > 0 | |
q, r = 0, n | |
assert n == (d * q) + r ## invariant!! | |
print('dividend = (divisor * quotient) + remainder') | |
print('%d == (%d * %d) + %d' % (n,d,q,r)) | |
while r >= d: | |
k, m = 0, 0 | |
def biggest_digit(n, c): | |
assert n >= 0 | |
s = str(n) | |
return int(s[:1 + c]), 10 ** (len(s) - c - 1) | |
for c in range(len(str(r))): | |
k, m = biggest_digit(r, c) | |
k = (k // d) | |
if k > 0: | |
break | |
print('increase quotient by (%d * %d).' % (k, m)) | |
print('decrease remainder by (%d * (%d * %d)).' % (d, k, m)) | |
print('%d == (%d * (%d + (%d * %d))) + (%d - (%d * %d * %d))' % (n,d,q,k,m,r,d,k,m)) | |
q, r = q + k * m, r - (d * k * m) | |
assert n == d * q + r | |
print('%d == (%d * %d) + %d' % (n,d,q,r)) | |
print('\nquotient = %d, remainder = %d\n' % (q, r)) | |
division(923, 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment