fork download
  1. def bitstring(x): return bin(x)[2:]
  2. def printlongdiv(lhs, rhs):
  3. rem = lhs
  4. div = rhs
  5. origlen = len(bitstring(div))
  6.  
  7. # first shift left until the leftmost bits line up.
  8. count = 1
  9. while (div | rem) > 2*div:
  10. div <<= 1
  11. count += 1
  12.  
  13. # now keep dividing until we are back where we started.
  14. quot = 0
  15. while count>0:
  16. quot <<= 1
  17. count -= 1
  18. print("%14s" % bitstring(rem))
  19. divstr = bitstring(div)
  20. if (rem ^ div) < rem:
  21. quot |= 1
  22. rem ^= div
  23.  
  24. print(1, " " * (11-len(divstr)), divstr[:origlen])
  25. else:
  26. print(0, " " * (11-len(divstr)), "0" * origlen)
  27. print(" " * (13-len(divstr)), "-" * origlen)
  28. div >>= 1
  29. print("%14s <<< remainder" % bitstring(rem))
  30. print(" -> %10s <<< quotient" % bitstring(quot))
  31.  
  32. printlongdiv(50,3)
  33.  
  34.  
  35.  
Success #stdin #stdout 0.12s 14124KB
stdin
Standard input is empty
stdout
        110010
1       11
        --
            10
0        00
         --
            10
0         00
          --
            10
0          00
           --
            10
1           11
            --
             1 <<< remainder
 ->      10001 <<< quotient