Use the array ADT to compute the addition and subtraction of two polynomials.
The interface of your program must look like this one:
Enter the degree of polynomial for p(x) : 5
Enter the coefficient of x^0 : 0
Enter the coefficient of x^1 : 4
Enter the coefficient of x^2 : 5
Enter the coefficient of x^3 : 0
Enter the coefficient of x^4 : 6
Enter the coefficient of x^5 : 4
Enter the degree of polynomial for q(x) : 3
Enter the coefficient of x^0 : 3
Enter the coefficient of x^1 : -2
Enter the coefficient of x^2 : 3
Enter the coefficient of x^3 : 10
First Polynomial p(x) = 4x^5 + 6x^4 + 5x^2 + 4x
Second Polynomial q(x) = 10x^3 + 3x^2 – 2x + 3
p(x) + q(x) = 4x^5 + 6x^4 +10x^3 + 8x^2 + 2x + 3
p(x) – q(x) = 4x^5 + 6x^4 – 10x^3 + 2x^2 + 6x – 3
The numbers in Red are entered by the user.
Hint:
Use 1D array to store the polynomials:
For the above example, the polynomials will be stored like this:
Index 0 1 2 3 4 5
p(x) Coefficient 0 4 5 0 6 4
Index 0 1 2 3
q(x) Coefficient 3 -2 3 10
#include <iostream>
#include <math.h>
using namespace std;
class Polynomial{
int *coefs, deg;
public:
Polynomial(){
coefs = NULL;
}
Polynomial(int degree){
this->deg = degree;
coefs = (int*) malloc(sizeof(int) * (degree + 1));
for(int i = 0; i <= degree; i++){
cout<<"Enter the coefficient of x^"<<i<<":";
cin>>coefs[i];
}
}
Polynomial operator+(const Polynomial &other){
Polynomial result;
if(this->deg > other.deg){
result.deg = this->deg;
result.coefs = (int *) malloc(sizeof(int) * (result.deg + 1));
int i = 0;
for(i = 0; i <= other.deg; i++){
result.coefs[i] = this->coefs[i] + other.coefs[i];
}
for(i; i <= result.deg; i++){
result.coefs[i] = this->coefs[i];
}
}
else{
result.deg = other.deg;
result.coefs = (int *) malloc(sizeof(int) * (result.deg + 1));
int i = 0;
for(i = 0; i <= this->deg; i++){
result.coefs[i] = this->coefs[i] + other.coefs[i];
}
for(i; i <= result.deg; i++){
result.coefs[i] = other.coefs[i];
}
}
return result;
}
Polynomial operator-(const Polynomial &other){
Polynomial temp;
temp.deg = other.deg;
temp.coefs = (int*) malloc(sizeof(int) * (other.deg + 1));
for(int i = 0; i <= other.deg; i++){
temp.coefs[i] = -1 * other.coefs[i];
}
return *this + temp;
}
void print(){
for(int i = this->deg; i >= 0; i--){
if(coefs[i] != 0){
if(coefs[i] < 0) cout<<" - ";
else if(i != this->deg) cout<<" + ";
cout<<abs(coefs[i]);
if(i == 1) cout<<"x";
else if(i != 0) cout<<"x^"<<i;
}
}
}
~Polynomial(){
if(coefs != NULL) delete this->coefs;
}
};
int main(){
int dp, dq;
cout<<"Enter the degree of polynomial for p(x):";
cin>>dp;
Polynomial p(dp);
cout<<"Enter the degree of polynomial for q(x):";
cin>>dq;
Polynomial q(dq);
cout<<"First Polynomial p(x) = "; p.print();
cout<<"\nSecond Polynomial q(x) = "; q.print();
cout<<"\np(x) + q(x) = "; (p + q).print();
cout<<"\np(x) - q(x) = "; (p - q).print();
return 0;
}
Comments
Leave a comment