Program to add two polynomials
Given two polynomials represented by two arrays, write a function that adds given two polynomials.
Example:
Input: A[] = {5, 0, 10, 6}
B[] = {1, 2, 4}
Output: sum[] = {6, 2, 14, 6}
The first input array represents "5 + 0x^1 + 10x^2 + 6x^3"
The second array represents "1 + 2x^1 + 4x^2"
And Output is "6 + 2x^1 + 14x^2 + 6x^3"We strongly recommend to minimize your browser and try this yourself first.
Addition is simpler than multiplication of polynomials. We initialize the result as one of the two polynomials, then we traverse the other polynomial and add all terms to the result.
add(A[0..m-1], B[0..n01])
1) Create a sum array sum[] of size equal to maximum of 'm' and 'n'
2) Copy A[] to sum[].
3) Traverse array B[] and do following for every element B[i]
sum[i] = sum[i] + B[i]
4) Return sum[].The following is the implementation of the above algorithm.
C++
// Simple C++ program to add two polynomials#include <iostream>using namespace std;// A utility function to return maximum of two integersint max(int m, int n) { return (m > n) ? m : n; }// A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyint* add(int A[], int B[], int m, int n){ int size = max(m, n); int* sum = new int[size]; // Initialize the product polynomial for (int i = 0; i < m; i++) sum[i] = A[i]; // Take every term of first polynomial for (int i = 0; i < n; i++) sum[i] += B[i]; return sum;}// A utility function to print a polynomialvoid printPoly(int poly[], int n){ for (int i = 0; i < n; i++) { cout << poly[i]; if (i != 0) cout << "x^" << i; if (i != n - 1) cout << " + "; }}// Driver program to test above functionsint main(){ // The following array represents polynomial 5 + 10x^2 + // 6x^3 int A[] = { 5, 0, 10, 6 }; // The following array represents polynomial 1 + 2x + // 4x^2 int B[] = { 1, 2, 4 }; int m = sizeof(A) / sizeof(A[0]); int n = sizeof(B) / sizeof(B[0]); cout << "First polynomial is \n"; printPoly(A, m); cout << "\nSecond polynomial is \n"; printPoly(B, n); int* sum = add(A, B, m, n); int size = max(m, n); cout << "\nsum polynomial is \n"; printPoly(sum, size); return 0;} |
Java
// Java program to add two polynomialsclass GFG {// A utility function to return maximum of two integers static int max(int m, int n) { return (m > n) ? m : n; }// A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectively static int[] add(int A[], int B[], int m, int n) { int size = max(m, n); int sum[] = new int[size];// Initialize the product polynomial for (int i = 0; i < m; i++) { sum[i] = A[i]; }// Take ever term of first polynomial for (int i = 0; i < n; i++) { sum[i] += B[i]; } return sum; }// A utility function to print a polynomial static void printPoly(int poly[], int n) { for (int i = 0; i < n; i++) { System.out.print(poly[i]); if (i != 0) { System.out.print("x^" + i); } if (i != n - 1) { System.out.print(" + "); } } }// Driver program to test above functions public static void main(String[] args) { // The following array represents polynomial 5 + 10x^2 + 6x^3 int A[] = {5, 0, 10, 6}; // The following array represents polynomial 1 + 2x + 4x^2 int B[] = {1, 2, 4}; int m = A.length; int n = B.length; System.out.println("First polynomial is"); printPoly(A, m); System.out.println("\nSecond polynomial is"); printPoly(B, n); int sum[] = add(A, B, m, n); int size = max(m, n); System.out.println("\nsum polynomial is"); printPoly(sum, size); }} |
Python3
# Simple Python 3 program to add two# polynomials# A utility function to return maximum# of two integers# A[] represents coefficients of first polynomial# B[] represents coefficients of second polynomial# m and n are sizes of A[] and B[] respectivelydef add(A, B, m, n): size = max(m, n); sum = [0 for i in range(size)] # Initialize the product polynomial for i in range(0, m, 1): sum[i] = A[i] # Take ever term of first polynomial for i in range(n): sum[i] += B[i] return sum# A utility function to print a polynomialdef printPoly(poly, n): for i in range(n): print(poly[i], end = "") if (i != 0): print("x^", i, end = "") if (i != n - 1): print(" + ", end = "")# Driver Codeif __name__ == '__main__': # The following array represents # polynomial 5 + 10x^2 + 6x^3 A = [5, 0, 10, 6] # The following array represents # polynomial 1 + 2x + 4x^2 B = [1, 2, 4] m = len(A) n = len(B) print("First polynomial is") printPoly(A, m) print("\n", end = "") print("Second polynomial is") printPoly(B, n) print("\n", end = "") sum = add(A, B, m, n) size = max(m, n) print("sum polynomial is") printPoly(sum, size) # This code is contributed by# Sahil_Shelangia |
C#
// C# program to add two polynomialsusing System;class GFG { // A utility function to return maximum of two integers static int max(int m, int n) { return (m > n) ? m : n; } // A[] represents coefficients of first polynomial // B[] represents coefficients of second polynomial // m and n are sizes of A[] and B[] respectively static int[] add(int[] A, int[] B, int m, int n) { int size = max(m, n); int[] sum = new int[size]; // Initialize the product polynomial for (int i = 0; i < m; i++) { sum[i] = A[i]; } // Take ever term of first polynomial for (int i = 0; i < n; i++) { sum[i] += B[i]; } return sum; } // A utility function to print a polynomial static void printPoly(int[] poly, int n) { for (int i = 0; i < n; i++) { Console.Write(poly[i]); if (i != 0) { Console.Write("x^" + i); } if (i != n - 1) { Console.Write(" + "); } } } // Driver code public static void Main() { // The following array represents // polynomial 5 + 10x^2 + 6x^3 int[] A = {5, 0, 10, 6}; // The following array represents // polynomial 1 + 2x + 4x^2 int[] B = {1, 2, 4}; int m = A.Length; int n = B.Length; Console.WriteLine("First polynomial is"); printPoly(A, m); Console.WriteLine("\nSecond polynomial is"); printPoly(B, n); int[] sum = add(A, B, m, n); int size = max(m, n); Console.WriteLine("\nsum polynomial is"); printPoly(sum, size); }}//This Code is Contributed// by Mukul Singh |
PHP
<?php// Simple PHP program to add two polynomials// A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyfunction add($A, $B, $m, $n){ $size = max($m, $n); $sum = array_fill(0, $size, 0); // Initialize the product polynomial for ($i = 0; $i < $m; $i++) $sum[$i] = $A[$i]; // Take ever term of first polynomial for ($i = 0; $i < $n; $i++) $sum[$i] += $B[$i]; return $sum;}// A utility function to print a polynomialfunction printPoly($poly, $n){ for ($i = 0; $i < $n; $i++) { echo $poly[$i]; if ($i != 0) echo "x^" . $i; if ($i != $n - 1) echo " + "; }}// Driver Code// The following array represents// polynomial 5 + 10x^2 + 6x^3$A = array(5, 0, 10, 6);// The following array represents// polynomial 1 + 2x + 4x^2$B = array(1, 2, 4);$m = count($A);$n = count($B);echo "First polynomial is \n";printPoly($A, $m);echo "\nSecond polynomial is \n";printPoly($B, $n);$sum = add($A, $B, $m, $n);$size = max($m, $n);echo "\nsum polynomial is \n";printPoly($sum, $size);// This code is contributed by chandan_jnu?> |
Javascript
<script>// Simple JavaScript program to add two// polynomials// A utility function to return maximum// of two integers// A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectively function add(A, B, m, n){ let size = Math.max(m, n); var sum = []; for (var i = 0; i < 10; i++) sum[i] = 0; // Initialize the product polynomial for(let i = 0;i<m;i++){ sum[i] = A[i]; } // Take ever term of first polynomial for (let i = 0;i<n;i++){ sum[i] += B[i]; } return sum; } // A utility function to print a polynomial function printPoly(poly, n){ let ans = ''; for(let i = 0;i<n;i++){ ans += poly[i]; if (i != 0){ ans +="x^ "; ans +=i; } if (i != n - 1){ ans += " + "; } } document.write(ans); } // Driver Code // The following array represents // polynomial 5 + 10x^2 + 6x^3 let A = [5, 0, 10, 6]; // The following array represents // polynomial 1 + 2x + 4x^2 let B = [1, 2, 4]; let m = A.length; let n = B.length; document.write("First polynomial is" + "</br>"); printPoly(A, m); document.write("</br>"); document.write("Second polynomial is" + "</br>"); printPoly(B, n); let sum = add(A, B, m, n); let size = Math.max(m, n); document.write("</br>"); document.write("sum polynomial is" + "</br>"); printPoly(sum, size); </script> |
Output:
First polynomial is 5 + 0x^1 + 10x^2 + 6x^3 Second polynomial is 1 + 2x^1 + 4x^2 Sum polynomial is 6 + 2x^1 + 14x^2 + 6x^3
Time complexity: O(m+n) where m and n are orders of two given polynomials.
Auxiliary Space: O(max(m, n))
Polynomial addition using Linked List
C++
// Program to add two polynomials represented// in linkedlist using recursion#include <iostream>using namespace std;// Node classclass Node {public: int coeff, power; Node* next; // Constructor of Node Node(int coeff, int power) { this->coeff = coeff; this->power = power; this->next = NULL; }};// Function to add polynomialsvoid addPolynomials(Node* head1, Node* head2){ // Checking if our list is empty if (head1 == NULL && head2 == NULL) return; // List contains elmements else if (head1->power == head2->power) { cout << " " << head1->coeff + head2->coeff << "x^" << head1->power << " "; addPolynomials(head1->next, head2->next); } else if (head1->power > head2->power) { cout << " " << head1->coeff << "x^" << head1->power << " "; addPolynomials(head1->next, head2); } else { cout << " " << head2->coeff << "x^" << head2->power << " "; addPolynomials(head1, head2->next); }}void insert(Node* head, int coeff, int power){ Node* new_node = new Node(coeff, power); while (head->next != NULL) { head = head->next; } head->next = new_node;}void printList(Node* head){ cout << "Linked List" << endl; while (head != NULL) { cout << " " << head->coeff << "x" << "^" << head->power; head = head->next; }}// Main functionint main(){ Node* head = new Node(5, 2); insert(head, 4, 1); Node* head2 = new Node(6, 2); insert(head2, 4, 1); printList(head); cout << endl; printList(head2); cout << endl << "Addition:" << endl; addPolynomials(head, head2); return 0;} |
Java
// java code for the above approach// Program to add two polynomials represented// in linkedlist using recursionimport java.util.*;// Node classclass Node { public int coeff, power; Node next; // Constructor of Node Node(int coeff, int power) { this.coeff = coeff; this.power = power; this.next = null; }}// Function to add polynomialspublic class Main { public static void addPolynomials(Node head1, Node head2) { // Checking if our list is empty if (head1 == null && head2 == null) return; // List contains elements else if (head1.power == head2.power) { System.out.print(" " + (head1.coeff + head2.coeff) + "x^" + head1.power + " "); addPolynomials(head1.next, head2.next); } else if (head1.power > head2.power) { System.out.print(" " + head1.coeff + "x^" + head1.power + " "); addPolynomials(head1.next, head2); } else { System.out.print(" " + head2.coeff + "x^" + head2.power + " "); addPolynomials(head1, head2.next); } } public static void insert(Node head, int coeff, int power) { Node new_node = new Node(coeff, power); while (head.next != null) { head = head.next; } head.next = new_node; } public static void printList(Node head) { System.out.println("Linked List"); while (head != null) { System.out.print(" " + head.coeff + "x" + "^" + head.power); head = head.next; } } // Main function public static void main(String[] args) { Node head = new Node(5, 2); insert(head, 4, 1); Node head2 = new Node(6, 2); insert(head2, 4, 1); printList(head); System.out.println(); printList(head2); System.out.println("\nAddition:"); addPolynomials(head, head2); }}// This code is contributed by Prince Kumar |
Linked List 5x^2 4x^1 Linked List 6x^2 4x^1 Addition: 11x^2 8x^1
Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively.
Auxiliary Space: O(m + n) where m and n are number of nodes in first and second lists respectively due to recursion.
This article is contributed by Harsh. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Implementation of a function that adds two polynomials represented as lists:
Approach
This implementation takes two arguments p1 and p2, which are lists representing the coefficients of two polynomials. The function returns a new list representing the sum of the two input polynomials.
The function first checks the lengths of the two input lists and pads the shorter list with zeros so that both lists have the same length. We then use the zip function to create pairs of corresponding coefficients from the two input lists, and the sum function to add the pairs together. The resulting sum is appended to a new list, which is returned at the end.
Python3
def add_polynomials(p1, p2): len1, len2 = len(p1), len(p2) if len1 < len2: p1 += [0] * (len2 - len1) else: p2 += [0] * (len1 - len2) return [sum(x) for x in zip(p1, p2)]p1 = [2, 0, 4, 6, 8]p2 = [0, 0, 1, 2]print(add_polynomials(p1, p2)) |
[2, 0, 5, 8, 8]
time complexity: O(n), where n is the max of length of two polynomials
space complexity : O(n). where n is the max of length of two polynomials





.gif)

Please Login to comment...