Write an algorithm that accepts two polynomials as input and prints the resultant polynomial due to the addition of input polynomials.
Answers
The C++ code to add two given polynomials is :-
1) #include <iostream>
using namespace std;
int max(int m, int n) { return (m > n)? m: n; }
int *add(int A[], int B[], int m, int n)
{
int size = max(m, n);
int *sum = new int[size];
for (int i = 0; i<m; i++)
sum[i] = A[i];
for (int i=0; i<n; i++)
sum[i] += B[i];
return sum;
}
void 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 << " + ";
}
}
int main()
{
int A[10] ;
for(int i=0; i<10;i++)
cin>>A[i];
int B[10] ;
for(int i=0; i<10;i++)
cin>>B[i];
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;
}
2) The given code works with following algorithm.
a) Create a sum array sum[] of size equal to maximum of 'm' and 'n'
b) Copy A[] to sum[].
c) Traverse array B[] and do following for every element B[i]
sum[i] = sum[i] + B[i]
d) Return sum[].