Home/Blog/Learn to Code/Learn to code the sum of two polynomials
Home/Blog/Learn to Code/Learn to code the sum of two polynomials

Learn to code the sum of two polynomials

10 min read
Jan 08, 2024
content
Introduction
Types of polynomials
Usage in computer science
Using a simple array
Sum using arrays
Optimization for sparse polynomial
Using parallel arrays
Sum using parallel arrays
Alternative approaches
Wrapping up and next steps
Continue learning to code

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

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:


Introduction#

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: f(x)=5x2+4x+3f(x) = 5x^2+4x+3

Remember that:

  • The absence of an exponent with xx means x1x^1.
  • The absence of the variable from a term means x0x^0.

We can also write it as f(x)=3x0+4x1+5x2f(x) = 3x^0+4x^1+5x^2, where 00, 11, and 22 are the exponents of xx and 33, 44, and 55 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!

Cover
Learn C++

C++ is a versatile language known for its efficiency and flexibility, widely used in industries like game development, finance, and system programming. This course dives deep into C++ programming foundations, focusing on practical problem-solving techniques. You will start by learning basic problem-solving skills using simple programs and execution sheets. Then, you'll explore decision-making, branching, loops, and manipulation of strings and arrays using C++ programming. Finally, the course will cover functions and complex program structures, ensuring a comprehensive grasp of the language's capabilities. By the end, you will be equipped with problem-solving skills, a solid understanding of C++ basics, and confidence in writing structured code, setting you on the path to becoming a proficient C++ developer.

8hrs
Beginner
4 Challenges
4 Quizzes


Types of polynomials#

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.


Usage in computer science#

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, O(n2)O(n^2) 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.

Cover
Learn Java

This course focuses exclusively on teaching Java to beginners and demystifies procedural programming by grounding each concept in a hands-on project. You’ll start by learning built-in input and output methods, followed by user-defined methods. As you progress, you'll explore basic data types and apply them in sequential, selective, and iterative program structures. Finally, you'll use these concepts to complete an engaging project. By the end, you'll develop a fascination with Java programming, making it an excellent start to a career in computing for anyone looking to learn Java.

6hrs
Beginner
60 Playgrounds
5 Quizzes


Using a simple array#

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 f(x)=3x0+4x1+5x2f(x) = 3x^0+4x^1+5x^2 can be written in simple text as:

    3x0 
    4x1 
    5x2

The number written after the variable represents the exponent.

Mapping of terms to array elements
Mapping of terms to array elements

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 coefficients
int 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;
}
Polynomial as a simple array or list of coefficients in C++

In the above code:

  • We declare an array or a list of coefficients. Its size is one more than the degree of the polynomial stored in it. If the degree of the polynomial is two, then the array size is three.
  • We use a loop to display each term:
    • First, we write the value of the array element.
    • Then, we write a string “x”.
    • At the end, we write the index.

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.


Sum using arrays#

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 f(x)=5+8x+6x3f(x)=5+8x+6x^3 as the first operand and g(x)=4+x2g(x)=4+x^2 as the second. The coefficients of x2x^2 and x1x^1 are 00 in f(x)f(x) and g(x)g(x), respectively.

#include <iostream>
using namespace std;
int main() {
// f(x) = 5 + 8x + 6x3
// g(x) = 4 + x2
int 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;
}
Showing the sum of two polynomials

In the above code:

  • We declare two arrays, f and g, to store two polynomials.
  • The size of both arrays is the same, and the missing terms are stored as having a 0 coefficient.
  • We display the sum of corresponding elements of both arrays using a loop.

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 + x2
int 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;
}
Storing the sum of two polynomials

Get Started!

Cover
Learn Python

This course is designed for you to learn Python from scratch, making it ideal for anyone interested in Python programming for beginners. Using Edward the robot to gamify concepts, you'll explore Python programming fundamentals, from built-in functions to user-defined functions and basic data types. You’ll also learn how to write programs using sequential, selective, and iterative structures. By completing hands-on projects, you'll gain the skills needed to kickstart your career as a Python developer and become a lifelong learner in computing.

10hrs
Beginner
80 Playgrounds
2 Quizzes

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.


Optimization for sparse polynomial#

A polynomial is sparse if it has very few nonzero coefficients compared to its degree. For example, 3x+x10+5x203x+x^{10}+5x^{20} 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.

Sparse polynomial stored as a simple array
Sparse polynomial stored as a simple array

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.


Using parallel arrays#

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, 3x+x10+5x203x+x^{10}+5x^{20} can be stored like so:

Sparse polynomial using two parallel arrays
Sparse polynomial using two parallel arrays

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 f
int 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;
}
Sparse polynomial stored using two parallel arrays

In the above code:

  • We declare two arrays or lists, fe and fc, to store the exponents and coefficients of ff. Its size should be equal to the number of nonzero terms in the polynomial to be stored.
  • We use a loop to display each term:
    • First, we write the element of the coefficient array.
    • Then, we write a string “x”.
    • At the end, we write the element of the exponent array.


Sum using parallel arrays#

The sum of two sparse polynomials is a bit more challenging:

  • The nonzero exponents may differ in two polynomials.
  • The number of terms in the resulting sum isn’t clear at the start. However, the sum of the size of both arrays is a safe bet.

Let’s take the sum of two sparse polynomials—f(x)=3x+x10+5x20f(x)=3x+x^{10}+5x^{20} and g(x)=2+6x10g(x)=2+6x^{10}— stored as two sets of parallel arrays. The following slides illustrate the steps to compute the sum.

canvasAnimation-image
1 / 9

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 polynomial
int fe[] = {1, 10, 20};
int fc[] = {3, 1, 5};
// ge and gc store g polynomial
int 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 counter
if ((f < lenf && g < leng) // Are f and g valid?
&& fe[f] == ge[g]) { // both exponents are equal
cout << 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;
}
Sum of two sparse polynomials

In the above code:

  • We use fe and fc to store the ff polynomial.

  • We use ge and gc to store the gg 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 ff if its exponent is smaller than the exponent of the current term in gg. Here, we pretest that ff has not finished yet.

    • Otherwise, we display the current term in gg because either ff has finished already or the exponent of the current term in gg is smaller than that in ff.

  • 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 polynomial
int fe[] = {1, 10, 20};
int fc[] = {3, 1, 5};
// ge and gc store g polynomial
int 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 safety
int 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 equal
hc[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;
}
Storing the sum of two sparse polynomials

In the above code:

  • The arrays 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.

  • The first loop stores the sum of elements to h when the exponents of both participating terms are equal.
  • The second loop displays the terms of h.

Learn C++ from Scratch

Cover
Learn C++ from Scratch

Learn C++ for free with this interactive course, and get a handle on one of the most popular programming languages in the world. You'll start with a simple hello world program and proceed to cover core concepts such as conditional statements, loops, and functions in C++, before moving on to more advanced topics like inheritance, classes, and templates, along with much more. By the time you're done, you'll be an intermediate level C++ developer, ready to take on your own projects.

10hrs
Beginner
127 Playgrounds
24 Quizzes


Alternative approaches#

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++.


Wrapping up and next steps#

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.

Continue learning to code#


Written By:
Aasim Ali
Join 2.5 million developers at
Explore the catalog

Free Resources