Friday, March 27, 2026

Generating Formatted Long Division Practice Problems

Here's a Python script I wrote to generate a bunch of random long division problems with solutions, showing work.

#!/usr/bin/env python3

import random

# Print 100 random 4-by-1 digit long division problems,
# showing the complete solution process.

def long_division(dividend, divisor):
    quotient = dividend // divisor
    remainder = dividend - quotient * divisor

    indent = " "*6

    print(indent + "      %4d R %d" % (quotient, remainder))
    print(indent + "    ------")
    print(indent + "%3d ) %4d" % (divisor, dividend))

    q = ((quotient // 1) % 10,
         (quotient // 10) % 10,
         (quotient // 100) % 10,
         (quotient // 1000) % 10)

    d = ((dividend // 1) % 10,
         (dividend // 10) % 10,
         (dividend // 100) % 10,
         (dividend // 1000) % 10)

    indent += " "*4

    rem = 0
    digit = 3

    # find the first non-zero quotient digit
    while digit > -1:
        rem = rem * 10 + d[digit]
        if q[digit] > 0:
            break
        digit -= 1
    if digit < 0:
        return

    while digit >= 0:

        # subtract the product from the remainder
        print(indent + "- %*d" % (4 - digit, q[digit] * divisor))
        print(indent + "-------")
        rem = rem - (q[digit] * divisor)
        print(indent + "  %*d" % (4 - digit, rem), end="")

        digit -= 1

        # find the next non-zero quotient digit, bringing more quotient
        # digits down

        while digit >= 0:
            rem = rem * 10 + d[digit]
            print("%d" % d[digit], end="")
            if q[digit] > 0:
                break
            digit -= 1

        print("")

for i in range(100):

    print("")
    print("-"*20)
    print("#%d" % (i+1))

    dividend = random.randint(1000,9999)
    divisor = random.randint(2,9)

    long_division(dividend, divisor)

This just prints the problems to stdout, and you can grep for the important lines if you want to remove the solutions:

$ python3 division.py > solutions
$ grep -E "\#|\)| ------$" solutions > problems

Here's a sample output:

--------------------
#1
             207 R 1
          ------
        6 ) 1243
          - 12
          -------
             043
          -   42
          -------
               1
--------------------
#2
             555 R 4
          ------
        9 ) 4999
          - 45
          -------
             49
          -  45
          -------
              49
          -   45
          -------
               4
--------------------
#3
             609 R 2
          ------
        6 ) 3656
          - 36
          -------
             056
          -   54
          -------
               2
--------------------
#4
            1014 R 3
          ------
        6 ) 6087
          - 6
          -------
            008
          -   6
          -------
              27
          -   24
          -------
               3

No comments:

Post a Comment