CS23B097_LAB4_Q3.cpp
#include<bits/stdc++.h> #include "Polynomial.h" using namespace std; #define rep(i,a,b) for(int i=a;i<b;i++) #define rev(i,a,b) for(int i=a;i>=b;i--) #define pb push_back Polynomial::Polynomial(int size){ coeffArray.resize(size); rep(i,0,size) coeffArray[i]=0; } void Polynomial::insertTerm(int coef, int exp){ coeffArray[exp] = coef; } Polynomial Polynomial::add(Polynomial &rhs){ int q = max(coeffArray.size(),rhs.coeffArray.size()); Polynomial sum(q); rep(i,0,q){ if(i<coeffArray.size()){ sum.coeffArray[i]+=coeffArray[i]; } if(i<rhs.coeffArray.size()){ sum.coeffArray[i]+=rhs.coeffArray[i]; } } return sum; } Polynomial Polynomial::mul(Polynomial &rhs){ int q = coeffArray.size()*rhs.coeffArray.size(); Polynomial pro(q); rep(i,0,q) pro.coeffArray[i]=0; rep(i,0,coeffArray.size()){ rep(j,0,rhs.coeffArray.size()){ pro.coeffArray[i+j]+=coeffArray[i]*rhs.coeffArray[j]; } } return pro; } void Polynomial::print(){ bool f = 0; rev(i,coeffArray.size()-1,0){ if(coeffArray[i]!=0){ if(!f) {f=1;cout<<coeffArray[i]<<"x^"<<i;} else cout<<" + "<<coeffArray[i]<<"x^"<<i; } } cout<<'\n'; } signed main(){ int n; cin>>n; vector<int>c; vector<int>e; int max = -1; rep(i,0,n){ int a,b; cin>>a>>b; c.pb(a);e.pb(b); if(b>max) max = b; } Polynomial p1(max+1); rep(i,0,n){ p1.insertTerm(c[i],e[i]); } int m; cin>>m; vector<int>c1; vector<int>e1; int max1 = -1; rep(i,0,m){ int a,b; cin>>a>>b; c1.pb(a);e1.pb(b); if(b>max1) max1 = b; } Polynomial p2(max1+1); rep(i,0,m){ p2.insertTerm(c1[i],e1[i]); } Polynomial s = p1.add(p2); Polynomial p = p1.mul(p2); s.print();p.print(); }
Leave a Comment