# Completing the square the way al-Khwarizmi did it, in Python

> Completing the square from al-Khwarizmi's Algebra (c. 820 CE): his 6 types of equation, the x^2 + 10x = 39 figure, the 2-root case, and tested Python.

Published 2026-11-15, 15 min read, Ancient algorithms

Source: https://prasad.tech/blog/al-khwarizmi-completing-the-square/

---

`x^2 + 10x = 39` is the first compound equation in al-Khwarizmi's book on algebra, written in Baghdad c. 820 CE. He solves it by completing the square: halve the 10, square the half, and add 25 to both sides, so the left side becomes the perfect square `(x + 5)^2` and `x = 3`. The rule works for any `x^2 + bx = c`, and he gives it in words, with a drawn square as proof.

My text is Frederic Rosen's 1831 English translation, which is in the public domain. I coded each of al-Khwarizmi's 6 types of equation in Python and tested them against the quadratic formula ([code on GitHub](https://github.com/prasadus92/ancient-algorithms)), for the series [Ancient algorithms, implemented](/ancient-algorithms/).

## The problem it solves

Here is the first compound problem in the book, in Rosen's translation:

> "one square, and ten roots of the same, amount to thirty-nine dirhems;" that is to say, what must be the square which, when increased by ten of its own roots, amounts to thirty-nine?

In modern notation that is `x^2 + 10x = 39`. A "root" is the unknown, `x`, and a "square" is `x^2`. The dirhem is a coin, and here it stands for a plain number. The answer is `x = 3`, and the square is 9.

The equation has a second solution, `x = -13`. Al-Khwarizmi works with lengths and amounts of money, so he gives only positive answers, and his rules are written to produce them.

## Who wrote it, and when

- **Muhammad ibn Musa al-Khwarizmi** (al-Khwārizmī; Rosen spells it Mohammed ben Musa) lived c. 780 to c. 850, according to Folkerts (2001), and worked in Baghdad among the scholars of the "House of Wisdom" (Bayt al-hikma) under the caliph al-Ma'mun.
- **The book** is *al-Kitab al-mukhtasar fi hisab al-jabr wa'l-muqabala*, "The compendious book on calculating by completion and reduction". In his preface al-Khwarizmi says that the caliph al-Ma'mun "has encouraged me to compose a short work on Calculating by (the rules of) Completion and Reduction".
- **The date, c. 820 CE,** is an inference. The preface addresses al-Ma'mun as caliph, and Folkerts (2001) gives his reign as 813 to 833. Folkerts also notes that al-Khwarizmi's arithmetic, which he dates c. 825, cites the Algebra, so the Algebra came first. c. 820 sits in that window; no source I read gives a year.
- **The translation** I quote is Frederic Rosen's *The Algebra of Mohammed ben Musa* (London, 1831), made from a manuscript in Oxford, with the Arabic text. Roshdi Rashed published a newer edition with an English translation in 2009.

## The 6 types of equation

Al-Khwarizmi works with 3 kinds of number: "roots, squares, and simple numbers relative to neither root nor square". Every coefficient is positive and every term sits on the side where it is added, so where we write 1 equation with signs he has 6 types (Rosen, pp. 5 to 13):

| # | Al-Khwarizmi's words | Modern form | His example | Answer |
|---|---|---|---|---|
| 1 | squares are equal to roots | `ax^2 = bx` | `x^2 = 5x` | 5 |
| 2 | squares are equal to numbers | `ax^2 = c` | `5x^2 = 80` | 4 |
| 3 | roots are equal to numbers | `bx = c` | `4x = 20` | 5 |
| 4 | squares and roots are equal to numbers | `x^2 + bx = c` | `x^2 + 10x = 39` | 3 |
| 5 | squares and numbers are equal to roots | `x^2 + c = bx` | `x^2 + 21 = 10x` | 3 or 7 |
| 6 | roots and numbers are equal to squares | `x^2 = bx + c` | `x^2 = 3x + 4` | 4 |

Types 1 to 3 need a division and at most a square root. Types 4 to 6 need the square completed. For all 6 he first reduces any number of squares to 1: "you reduce them to one single square, and in the same proportion you reduce also the roots and simple numbers". So `2x^2 + 10x = 48` becomes `x^2 + 5x = 24`, and `x^2/2 + 5x = 28` becomes `x^2 + 10x = 56`.

## The rules, in Rosen's translation

### Type 4: squares and roots equal numbers

> The solution is this: you halve the number of the roots, which in the present instance yields five. This you multiply by itself; the product is twenty-five. Add this to thirty-nine; the sum is sixty-four. Now take the root of this, which is eight, and subtract from it half the number of the roots, which is five; the remainder is three. This is the root of the square which you sought for; the square itself is nine.
>
> Rosen (1831), p. 8

In symbols: `x = sqrt((b/2)^2 + c) - b/2`.

### Type 5: squares and numbers equal roots, with 2 answers

> Halve the number of the roots; the moiety is five. Multiply this by itself; the product is twenty-five. Subtract from this the twenty-one which are connected with the square; the remainder is four. Extract its root; it is two. Subtract this from the moiety of the roots, which is five; the remainder is three. This is the root of the square which you required, and the square is nine. Or you may add the root to the moiety of the roots; the sum is seven; this is the root of the square which you sought for, and the square itself is forty-nine.
>
> Rosen (1831), p. 11

He then states the 3 cases that follow from the sign of `(b/2)^2 - c`:

> if the product be less than the number of dirhems connected with the square, then the instance is impossible; but if the product be equal to the dirhems by themselves, then the root of the square is equal to the moiety of the roots alone, without either addition or subtraction.
>
> Rosen (1831), p. 12

This is the discriminant test: no positive root, 1 double root, or 2 positive roots. He adds that this is the only type in which "both addition and subtraction may be employed".

### Type 6: roots and numbers equal squares

For `x^2 = 3x + 4` he halves 3 to get 1½, squares it to get 2¼, adds 4 to get 6¼, takes the root, 2½, and adds the half: `2½ + 1½ = 4` (Rosen, pp. 12 and 13).

### My summary of the rules

1. Divide everything by the number of squares.
2. Halve the number of roots and multiply the half by itself.
3. Type 4: add the number, take the root, subtract the half.
4. Type 6: add the number, take the root, add the half.
5. Type 5: subtract the number. If the result is negative, there is no answer; if it is 0, the half is the answer; otherwise take the root and subtract it from the half, or add it to the half.

## What the text leaves open

1. **Irrational answers.** Every worked example in this part of the book comes out to a whole number or a simple fraction. The rule "take the root" says nothing about roots that are not exact. My code returns an exact fraction when the root is exact and a float when it is not.
2. **Which of the 2 answers in type 5.** He says to "try its solution by addition, and if that do not serve, then subtraction certainly will". That reads as a check against the problem's own conditions. The code returns both.
3. **Zero.** Type 1, `x^2 = 5x`, also has `x = 0`. He gives only 5.
4. **Negative answers.** `x^2 + 10x = 39` has the root `-13`, which the text never mentions.

## Completing the square on a drawn figure

Al-Khwarizmi proves the type 4 rule with a figure (Rosen, pp. 13 to 15). The square `AB` has the unknown side `x`. Ten roots are `10x`, an area of 10 strips, so he splits them into 4 rectangles of breadth 2½, one along each side:

> we may take one-fourth of ten, that is to say, two and a half, and combine it with each of the four sides of the figure.

The square plus the 4 strips is `x^2 + 10x`, which the problem says is 39. The cross shape is missing 4 corners, each 2½ by 2½. He fills them in:

> In order to compensate for this want and to complete the quadrate, we must add (to that which we have already) four times the square of two and a half, that is, twenty-five.

<figure class="dg" aria-label="Al-Khwarizmi's figure for x squared plus 10x equals 39. A square of unknown side x sits in the middle. A strip 2 and a half wide lies along each of its 4 sides, so the square and strips make 39. The 4 empty corners are squares of 2 and a half by 2 and a half, 25 in total. The completed great square has area 64 and side 8, so x is 8 minus 2 and a half minus 2 and a half, which is 3.">
<div class="dg-canvas">
</div>
<figcaption>The square of side x, 4 strips of breadth 2½ (one quarter of the 10 roots each), and 4 corner squares of 6¼. The strips and the inner square make 39, and the corners add 25, so the great square is 64.</figcaption>
</figure>

The great square is 39 + 25 = 64, so its side is 8. The side is `x` plus 2½ at each end, so `x = 8 - 5 = 3`.

He then explains why the rule says "halve and square" when the figure used quarters: "the fourth of any number multiplied by itself, and then by four, is equal to the product of the moiety of that number multiplied by itself". In symbols, `4 × (b/4)^2 = (b/2)^2`. He also gives a second figure with 2 rectangles of 5 by `x` on 2 sides and 1 corner square of 25, which reaches the same 64 (Rosen, pp. 15 and 16). The code builds both figures and checks that they agree.

## Why it works

In modern algebra, add `(b/2)^2` to both sides of `x^2 + bx = c`:

$$x^2 + bx + \left(\tfrac{b}{2}\right)^2 = c + \left(\tfrac{b}{2}\right)^2 \quad\Longrightarrow\quad \left(x + \tfrac{b}{2}\right)^2 = c + \left(\tfrac{b}{2}\right)^2$$

Take the positive square root and subtract `b/2`. That is type 4. The figure is the same identity read as areas: the left side is the great square, of side `x + b/2`.

Type 5 is `x^2 - bx = -c`. Adding `(b/2)^2` gives `(x - b/2)^2 = (b/2)^2 - c`, so `x = b/2 ± sqrt((b/2)^2 - c)`. The right side can be negative, zero or positive, which gives his "impossible", 1 answer and 2 answers. Both answers are positive whenever they exist, since the root is smaller than `b/2` when `c` is positive. That is why only this type has 2 answers in his scheme.

Type 6 is `x^2 - bx = c`, which gives `(x - b/2)^2 = (b/2)^2 + c` and `x = b/2 + sqrt((b/2)^2 + c)`. The minus sign would give a negative answer, which he leaves out.

## The Python

This version covers the 3 compound types and runs on its own. It uses exact fractions, so the answers come out as al-Khwarizmi writes them.

```python
from fractions import Fraction
from math import isqrt


def root(q: Fraction) -> Fraction:
    """Exact square root of a fraction that is a perfect square."""
    top, bottom = isqrt(q.numerator), isqrt(q.denominator)
    assert top * top == q.numerator and bottom * bottom == q.denominator, f"{q} is not a square"
    return Fraction(top, bottom)


def compound(kind: str, squares: Fraction, roots: Fraction, number: Fraction) -> list[Fraction]:
    """Al-Khwarizmi's rule for his 3 compound types, with all coefficients positive."""
    b, a = Fraction(roots) / squares, Fraction(number) / squares  # reduce to 1 square
    half = b / 2  # halve the number of the roots
    product = half * half  # multiply it by itself
    if kind == "squares and roots equal numbers":
        return [root(product + a) - half]
    if kind == "roots and numbers equal squares":
        return [root(product + a) + half]
    if kind == "squares and numbers equal roots":
        if product < a:
            return []  # "the instance is impossible"
        if product == a:
            return [half]
        return [half - root(product - a), half + root(product - a)]
    raise ValueError(f"unknown type: {kind}")


print(compound("squares and roots equal numbers", 1, 10, 39))  # x^2 + 10x = 39
print(compound("squares and roots equal numbers", Fraction(1, 2), 5, 28))  # x^2/2 + 5x = 28
print(compound("squares and numbers equal roots", 1, 10, 21))  # x^2 + 21 = 10x
print(compound("roots and numbers equal squares", 1, 3, 4))  # 3x + 4 = x^2
```

It prints:

```text
[Fraction(3, 1)]
[Fraction(4, 1)]
[Fraction(3, 1), Fraction(7, 1)]
[Fraction(4, 1)]
```

The [repo version](https://github.com/prasadus92/ancient-algorithms/blob/main/src/ancient_algorithms/completing_square.py) has 1 function per type, named after his wording. Each takes the keywords `squares`, `roots` and `number`, so a coefficient cannot land in the wrong place. It falls back to a float when a root is irrational, and builds the drawn square as a record with the strips, corners, great square and side. The tests check:

- all 14 worked examples in Rosen's pp. 6 to 13, including the reductions `2x^2 + 10x = 48` and `x^2/2 + 5x = 28`;
- the 2 answers 3 and 7 for `x^2 + 21 = 10x`, and the impossible and single-answer cases;
- both figures for `x^2 + 10x = 39`: 4 strips of 2½ with 4 corners of 6¼, and 2 rectangles of 5 with 1 corner of 25, each giving 64, 8 and 3;
- property tests with Hypothesis: for random positive whole-number coefficients, each of types 4, 5 and 6 returns the positive roots of the quadratic formula.

## Against the quadratic formula

The modern formula solves `ax^2 + bx + c = 0` in one line:

$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$

It is the same computation. Divide by `a` and write `p = b/a`, `q = c/a`, and the formula becomes `x = -p/2 ± sqrt((p/2)^2 - q)`: halve, square, subtract, take the root, move by the half. What changed is the bookkeeping:

- **Signs.** With negative numbers allowed, al-Khwarizmi's 3 compound types collapse into 1 equation. Type 4 is `p > 0` and `q < 0`, type 5 is `p < 0` and `q > 0`, type 6 is `p < 0` and `q < 0`.
- **Answers.** The formula returns every real root, negative ones included. His rules return the positive ones.
- **Proof.** The formula is proved by algebra on symbols. He proves each rule with a figure, because in his book a square is an area and a root is a length.

The property tests confirm that, for positive coefficients, his rules and the formula give the same positive roots.

## Parallels and lineage

- **Old Babylonian tablets, c. 1800 to 1600 BCE.** The tablet BM 13901, problem 1, reads in Høyrup's translation: "The surface and my confrontation I have heaped: 45′ is it." That is `x^2 + x = 3/4` in base 60. The scribe halves the 1, squares the half to get 15′, adds it to 45′ to get 1, takes the root, 1, and removes the 30′ to leave 30′, which is ½. The steps match al-Khwarizmi's type 4 rule, and the repo's test runs this problem through it. Høyrup calls it a "cut-and-paste procedure": half of the strip is moved round to a second side, and the empty corner square is filled in.
- **Indian mathematics.** Rosen's preface says Brahmagupta and Bhaskara "give dogmatical precepts, unsupported by argument", in verse, and contrasts this with al-Khwarizmi's geometric proofs. Rosen conjectures that part of the book came from an Indian source.
- **Greek geometry.** Rosen (1831) argued that al-Khwarizmi did not borrow from Diophantus, whom he believed reached Arabic only with Abu'l-Wafa in the 10th century. Folkerts (2001) says the geometric proofs "were not taken over from Greek writings", such as Euclid's *Elements*.
- **The Latin West.** The first part of the Algebra was translated into Latin twice in the 12th century, by Robert of Chester (Segovia, 1145) and by Gerard of Cremona (Toledo), according to Folkerts (2001). Rosen quotes the opening of Cardano's *Ars Magna*, which names "Mahomete, Mosis Arabis filio" as the one with whom the art began.

## What is debated

- **The date.** c. 820 is an inference from the dedication and from the order of his books. No source I read gives a year.
- **Where the method came from.** Rosen (1831) argued for an Indian source. Folkerts (2001) writes that "it is still not known which sources he used", and that Babylonian and Indian results, and perhaps an oral tradition, may have reached him in some form. The Babylonian tablets show the same steps about 2,500 years earlier.
- **What al-jabr means.** Rosen translates the title phrase as "Completion and Reduction". Merriam-Webster glosses *al-jabr* as "the reduction". The 12th-century Latin arithmetic based on al-Khwarizmi renders it "restaurationis et oppositionis", of restoration and opposition. The word *algebra* comes from *al-jabr* in any case.
- **"First".** A marginal note in the Oxford manuscript, which Rosen quotes, calls it "the first book written on (the art of calculating by) completion and reduction by a Mohammedan". Rosen himself says al-Khwarizmi was "not the inventor of the Art".

## Key takeaways

- Al-Khwarizmi's Algebra (Baghdad, c. 820 CE) sorts equations with positive terms into 6 types and gives a rule in words for each.
- For "squares and roots equal numbers", `x^2 + 10x = 39`, the rule is: halve 10, square to 25, add to get 64, take the root 8, subtract 5, answer 3.
- He proves it with a square of side `x`, 4 strips of 2½ and 4 corner squares of 6¼, which complete a square of 64.
- `x^2 + 21 = 10x` has 2 answers, 3 and 7, and his test for "impossible" is the modern discriminant test.
- The rules give the same positive roots as the quadratic formula, which the repo checks on random coefficients. The same steps appear on an Old Babylonian tablet 2,500 years earlier.

## Sources

- F. Rosen, [*The Algebra of Mohammed ben Musa*](https://archive.org/details/algebraofmohamme00khuwuoft), edited and translated. Oriental Translation Fund, London, 1831. Pp. 5 to 20 cover the 6 types and the 4 figures. Public domain.
- R. Rashed, *Al-Khwarizmi: The Beginnings of Algebra*. Saqi, London, 2009. Arabic text and English translation.
- J. Høyrup, [*Algebra in Cuneiform: Introduction to an Old Babylonian Geometrical Technique*](https://mprl-series.mpg.de/textbooks/2/). Max Planck Research Library for the History and Development of Knowledge, 2017. Chapter 3 translates BM 13901, problem 1.
- M. Folkerts, ["Early texts on Hindu-Arabic calculation"](https://epub.ub.uni-muenchen.de/15927/1/early_texts.pdf). *Science in Context* 14, 2001. On the order of al-Khwarizmi's books and the Latin translations.
- Merriam-Webster, ["algebra"](https://www.merriam-webster.com/dictionary/algebra), etymology. Read 15 November 2026.

---

## Common questions

**How do you complete the square?**

For x^2 + bx = c: halve b, square the half, and add it to both sides. The left side becomes (x + b/2)^2, so x + b/2 is the square root of c + (b/2)^2, and x is that root minus b/2. For x^2 + 10x = 39: half of 10 is 5, 25 + 39 = 64, the root is 8, and 8 - 5 = 3. This is al-Khwarizmi's own example.

**Who invented completing the square?**

No single person. An Old Babylonian tablet, BM 13901 (c. 1800 to 1600 BCE), solves a problem in which the area of a square plus its side is 45 sixtieths, by halving, squaring, adding and taking a root, the same steps. Al-Khwarizmi (c. 820 CE) sorted equations into 6 types, gave the rule for each in words, and proved it with a drawn square.

**What does al-jabr mean?**

Al-jabr is the first word of the operation in al-Khwarizmi's title, al-jabr wa'l-muqabala. Rosen (1831) translates the phrase as 'completion and reduction', and the 12th-century Latin arithmetic based on al-Khwarizmi glosses it as 'restoration and opposition'. The English word algebra comes from al-jabr through Medieval Latin.

**What are al-Khwarizmi's 6 types of equations?**

With all coefficients positive: squares equal roots (ax^2 = bx), squares equal numbers (ax^2 = c), roots equal numbers (bx = c), squares and roots equal numbers (x^2 + bx = c), squares and numbers equal roots (x^2 + c = bx) and roots and numbers equal squares (x^2 = bx + c). Only the last 3 need completing the square.
