The use of polynomials is fundamental to the field of computer science. There are various ways of dealing with them in programming. We’ll only discuss a couple of them, focusing on the readers with little background knowledge of programming. The scope of this blog is restricted to single-variable polynomials and the addition operation of two such polynomials.
Let’s dive right in!
We’ll cover:
A polynomial is a mathematical expression consisting of variables, their coefficients, and their exponents combined using arithmetic operations. Polynomials are fundamental in algebra. They are used in various physics, engineering, computer science, and business fields for modeling real-world events.
Here is a sample polynomial:
Remember that:
We can also write it as , where , , and are the exponents of and , , and are their coefficients, respectively. The exponent is noted in increasing order in the second option, which seems more convenient when implementing it in programming.
The above sample is called the quadratic polynomial because its degree is two. The degree of a polynomial is determined from the highest exponent of the variable.
Get Started!
This beginner-friendly course teaches C++ through a practical, hands-on approach. You’ll begin by learning how to communicate with the machine through input/output, simple calculations, and variables. Then, you’ll build programs to make decisions and repeat actions using conditionals and loops. As you progress, you’ll learn how to organize your code using functions, store data with arrays and vectors, and apply your knowledge by building mini projects like a number guessing game and a contact book. These exercises are designed to help you build confidence and reinforce your understanding. In the final section, you’ll build a complete project that combines all your skills in a creative, interactive program. Whether starting a tech career or just curious about coding, this course will give you a solid foundation in procedural C++ programming.
The types of polynomials are termed constant, linear, quadratic, or cubic based on whether their degree is zero, one, two, or three, respectively. The polynomials with the degree above three are generally termed higher-degree polynomials. The addition, subtraction, multiplication, and division operations can be performed on two or more polynomials.
Polynomials can involve multiple variables. They are termed univariate, bivariate, or trivariate based on if the number of variables is one, two, or three. The general term multivariate is used for polynomials involving two or more variables.
The focus of this blog is only on storage and addition of univariate polynomials. Of course, the same techniques can be extended to deal with other types and operations.
Polynomials are important in various subjects of computer science. Following are a few examples that highlight their significance:
Polynomials are used in relation to the time complexity of algorithms in the form of Big O notation. For example, is an upper bound on the time complexity of some sorting algorithms.
Polynomials are essential in scientific computing. For example, they are used to find the relationship between a goal and the set of points through interpolation.
Polynomials are also used in error detection and correction codes. For instance, the popular cyclic redundancy check (CRC) uses polynomials to detect errors in data transmission.
Polynomials are fundamental in computer graphics for designing smooth curves and surfaces.
Polynomials are used in numerical methods for solving equations, integrating functions, and approximating complex functions.
Polynomials are also useful in machine learning. They are used to find the relationship between variables through regression.
Polynomials are used in cryptography, including public keys and digital signatures.
Understanding how to store polynomials and perform operations on them is important for programmers.
You’ll start Java with the basics, such as printing messages, doing math, and working with user input, before exploring loops, conditionals, and object-oriented programming. Along the way, you’ll build real console apps, like games and menu systems, while learning how to structure your code using classes, methods, and objects. This course emphasizes hands-on learning and real-world modeling, making Java feel less intimidating and more intuitive. Whether you’re aiming to become an Android developer or backend engineer, or just want a solid foundation in programming, this course will help you write clean, structured code and confidently take your first step into software development. You need to know absolutely nothing about programming before your first lesson.
A univariate polynomial can be stored using a simple array. Considering the array index as the exponent of the variable, the coefficients can be stored as values for the corresponding exponent. The following text and diagram illustrate the polynomial representation in the program output and as an array in the memory.
The sample polynomial can be written in simple text as:
3x0
4x1
5x2
The number written after the variable represents the exponent.
The following code stores the sample polynomial:
#include <iostream>using namespace std;int main() {// index 0,1,2 refers to the exponent of x// values 3,4,5 refers to the related coefficientsint f[] = {3, 4, 5};int len = sizeof(f)/sizeof(int);for (int i=0;i<len;i++) {cout << f[i] << "x" << i << endl;}return 0;}
In the above code:
“x”
.We had to convert the numeric values to strings for concatenation during the display in Python and Ruby. There are other ways of doing the same task.
Now, we are ready to perform the addition of two polynomials. We achieve this by summing the corresponding elements of two arrays in the following code, taking as the first operand and as the second. The coefficients of and are in and , respectively.
#include <iostream>using namespace std;int main() {// f(x) = 5 + 8x + 6x3// g(x) = 4 + x2int f[] = {5, 8, 0, 6};int g[] = {4, 0, 1, 0};int len = sizeof(f)/sizeof(int);for (int i = 0; i < len; i++) {cout << f[i]+g[i] << "x" << i << endl;}return 0;}
In the above code:
f
and g
, to store two polynomials.0
coefficient.The size of the larger array is also used for the other array.
We can store the sum of the two polynomials in a third variable, as shown in the following code:
#include <iostream>using namespace std;int main() {// f(x) = 5 + 8x + 6x3// g(x) = 4 + x2int f[] = {5, 8, 0, 6};int g[] = {4, 0, 1, 0};const int len = sizeof(f)/sizeof(int);int h[len];for (int i = 0; i < len; i++) {h[i] = f[i]+g[i];}for (int i = 0; i < len; i++) {cout << h[i] << "x" << i << endl;}return 0;}
Get Started!
This course uses an active learning approach to teach Python programming to beginners. You’ll interact with the code from the start, using everyday logic and fun challenges to build confidence. You will learn essential programming concepts through interactive examples and mini projects like input/output, decision-making, error handling, and simple logic. Whether new to coding or just starting with Python, this course provides the perfect foundation to develop your problem-solving skills and easily write your programs. More than anything else, this course aims to make you a lifelong learner and serve as a strong starting point for a successful career in computing. You don’t need any programming experience to begin.
In the above code:
The array h
stores the sum of f
and g
.
The size of all the arrays equals the highest degree among both polynomials.
The first loop stores the sum of elements to h
.
The second loop displays the terms of h
.
A polynomial is sparse if it has very few nonzero coefficients compared to its degree. For example, is a sparse polynomial that can be stored as shown below. The box sizes of nonzero values are only adjusted to fit the term text; they have no special meaning.
The use of a simple array demands a lot of space for zero terms in a sparse polynomial. One efficient yet simple way is to use parallel arrays to store a sparse polynomial, as discussed below.
One space-efficient way to store a sparse polynomial is to use two parallel arrays. One of them is to store the exponent of a term, and the other one is to store the coefficient of the same term. For example, can be stored like so:
The following code stores the sample sparse polynomial:
#include <iostream>using namespace std;int main() {// f(x) = 3x + x10 + 5x20// fe stores exponents of f// fc stores coefficients of fint fe[] = {1, 10, 20};int fc[] = {3, 1, 5};const int len = sizeof(fe)/sizeof(int);for (int i = 0; i < len; i++) {cout << fc[i] << "x" << fe[i] << endl;}return 0;}
In the above code:
fe
and fc
, to store the exponents and coefficients of . Its size should be equal to the number of nonzero terms in the polynomial to be stored.“x”
.
The sum of two sparse polynomials is a bit more challenging:
Let’s take the sum of two sparse polynomials— and — stored as two sets of parallel arrays. The following slides illustrate the steps to compute the sum.
In the following code, we’re not storing the result in a new pair of parallel arrays. We are just displaying the sum. In this case, the number of iterations of the loop is not clear at the start because of the first challenge mentioned above.
#include <iostream>using namespace std;int main() {// f(x) = 3x + x10 + 5x20// g(x) = 2 + 6x10// fe and fc store f polynomialint fe[] = {1, 10, 20};int fc[] = {3, 1, 5};// ge and gc store g polynomialint ge[] = {0, 10};int gc[] = {2, 6};const int lenf = sizeof(fe)/sizeof(int);const int leng = sizeof(ge)/sizeof(int);int f = 0, g = 0, i = 0;while (f < lenf || g < leng) {i++; // iteration counterif ((f < lenf && g < leng) // Are f and g valid?&& fe[f] == ge[g]) { // both exponents are equalcout << fc[f]+gc[g] << "x" << fe[f] << endl;f++; g++;}else {if ((f < lenf && g >= leng) // g already finished|| fe[f] < ge[g]) {cout << fc[f] << "x" << fe[f] << endl;f++;}else { // f already finished OR ge[g] < fe[f]cout << gc[g] << "x" << ge[g] << endl;g++;}}}cout << "The size of new array should be: " << i << endl;return 0;}
In the above code:
We use fe
and fc
to store the polynomial.
We use ge
and gc
to store the polynomial.
We use three counters:
f
to track the index of fe
(and fc
).
g
to track the index of ge
(and gc
).
i
to track the total iterations of the loop. It states the number of terms in the resulting polynomial.
The loop terminates when both polynomials are finished: the condition f < lenf || g < leng
becomes false.
We display the sum of two coefficients if both exponents are the same: fe[f] == ge[g]
. Here, we also pretest that both counters are valid.
Otherwise, we display the term with a smaller exponent from the current terms in both polynomials.
We display the current term in if its exponent is smaller than the exponent of the current term in . Here, we pretest that has not finished yet.
Otherwise, we display the current term in because either has finished already or the exponent of the current term in is smaller than that in .
After the loop, we display the total number of iterations, which indicates the number of terms in the resulting polynomial.
We can store the sum of the two sparse polynomials in a third polynomial, as shown in the following code:
#include <iostream>using namespace std;int main() {// f(x) = 3x + x10 + 5x20// g(x) = 2 + 6x10// fe and fc store f polynomialint fe[] = {1, 10, 20};int fc[] = {3, 1, 5};// ge and gc store g polynomialint ge[] = {0, 10};int gc[] = {2, 6};const int lenf = sizeof(fe)/sizeof(int);const int leng = sizeof(ge)/sizeof(int);const int lenh = lenf + leng;// using the sum of both lengths for safetyint he[lenh];int hc[lenh];int f = 0, g = 0, i = 0;while (f < lenf || g < leng) {if ((f < lenf && g < leng) // Are f and g valid?&& fe[f] == ge[g]) { // both exponents are equalhc[i] = fc[f]+gc[g];he[i] = fe[f];f++; g++;}else {if ((f < lenf && g >= leng) // g already finished|| fe[f] < ge[g]) {hc[i] = fc[f];he[i] = fe[f];f++;}else { // f already finished OR ge[g] < fe[f]hc[i] = gc[g];he[i] = ge[g];g++;}}i++; // iteration counter}for (int h = 0; h < i; h++) {cout << hc[h] << "x" << he[h] << endl;}return 0;}
In the above code:
he
and hc
are used to store the sum of fc
and gc
for their corresponding exponents stored in fe
and ge
.
The resulting arrays should be large enough to store the terms in the union of exponents of both operands. If both polynomials have no common exponent, the resulting arrays should have a size equal to the sum of the sizes of both operands.
h
when the exponents of both participating terms are equal.h
.Learn C++ from Scratch
Learn C++ for free with this interactive course, and get a hands-on experience of one of the most popular programming languages in the world. You’ll start with a simple “Hello World” program and then move on to core concepts such as conditional statements, loops, and functions in C++. Then, you’ll explore more advanced topics like inheritance, classes, and templates, along with much more. After completing this course, you’ll be an intermediate-level C++ developer, ready to take on your own projects.
So far, we’ve only used the int
type values. However, these codes can be easily converted to handle the float
or double
type values.
The logic of the code demonstrated above can be coded using other components of programming languages. For example, C++ provides the facility of an efficient implementation called vector
. Another alternative for dynamic memory allocation is linked-list.
The two arrays to store the sparse polynomial can be better organized with the use of a struct
in C++, as shown below:
struct term {
int exponent, coefficient;
};
Then, a single term
array can work as two parallel int
arrays, as illustrated above.
An object-oriented approach can provide the benefits of using
class
in C++.
Polynomials are one of the most important topics in computer science. The storage and sum of polynomials is an interesting programming exercise. We have seen the implementation of polynomials through arrays/lists in various programming languages.
Happy learning, and keep growing!
To continue learning these concepts and more, check out Educative’s Become a C++ Programmer, Become a Java Developer, and Become a Python Developer paths.
Free Resources