Polynomial is an important topic in High School maths curriculum. There are many online courses that explain the topic in great details with lots of examples and sample exercises. Wouldn’t it be interesting if we can generate polynomials of given degree programmatically? It turns out that this is not such a hard problem after all.

Out of interest, I decided to experiment with this idea in Prolog. Why Prolog? No doubt, this can be implemented in any other language such as Python, Lisp, C++, Rust, etc., but I chose Prolog because polynomials have a well-defined syntax and structure, and this can be elegantly represented in Prolog in terms of Definite Clause Grammar (DCG) rules. Although DCGs are typically used as a “parsing” mechanism, we can use them for “generation” as well. Interested readers may go through my earlier article on “Generating Poetry in Prolog”.

The core generation logic is shown in the following figure:

Generating Polynomials – Main Clauses

“basic_expr” models a single term. The clauses “polynomial_1”, “polynomial_2a”, and “polynomial_2b” cover multiple terms. “polynomial2” helps in randomly choosing or ignoring a term of specific degree.

The main clause for polynomial generation is “polynomial”. It takes a “variable” and “degree” as arguments and generates a polynomial of that degree, using the supplied variable.

In line 24, the clause “polynomial_equation” builds upon the polynomial by turning it into an equation, where the RHS is zero.

A few other clauses act as helpers in the generation process. For example, the “add_operator” randomly chooses a “+” or “-“ to combine multiple terms. See this figure:

Helper Code

The sample output, when run inside SICStus Prolog IDE, looks like this:

Generated Polynomial Equations

The “generate” predicate takes an integer argument and prints that many polynomial equations.

Although this is an example of “univariate” polynomial, the program can be extended to handle multiple variables also.

The code has been tested in SICStus Prolog 4.8. You can download the source here.

Have a nice weekend!