fork(24) 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(0x4d0, 13)
  33.  
  34.  
Success #stdin #stdout 0.01s 9992KB
stdin
Standard input is empty
stdout
   10011010000
1  1101
   ----
    1001010000
1   1101
    ----
     100010000
1    1101
     ----
      10110000
1     1101
      ----
       1100000
1      1101
       ----
          1000
0       0000
        ----
          1000
0        0000
         ----
          1000
1         1101
          ----
           101 <<< remainder
 ->   11111001 <<< quotient