I am trying to write a function for simplifying terms in a polynomial:
Suppose that we can represent each terms by a two-member int array which the first member shows variable and the second member is the coefficient. for example 4a and 3b could be represented by (1, 4) and (2, 3), respectively. in these examples we have shown the variables (a, b, ..) by an integer based on alphabetic order (a:1, b:2, c:3, ...).
Therefore, a polynomial could be represented as a vector<-int*> of these terms. for example 4a+2b+10c could be shown like {(1,4), (2,2), (3,10)}. Now, the goal is to simplify a polynomial. for example:
2a+3c-a+5t-3c = a+5t
I have written a code in C++ to do this job but it's super slow for large polynomials.
void simplify (vector<int*> &p)
{
vector<int*>:: iterator it1 = p.begin();
vector<int*>:: iterator it2;
while (it1!=p.end())
{
if ((*it1)[1]!=0) // if the coefficient is not equal to zero
{
it2 = it1+1;
while (it2!=p.end())
{
if ((*it1)[0]==(*it2)[0]) //if the variables are similar
{
(*it1)[1] += (*it2)[1];
(*it2)[1]=0; //set the coefficient equal to zero
}
it2++;
}
}
it1++;
}
it1 = p.begin();
while (it1!=p.end()) //removing the terms with zero coefficient
{
if ((*it1)[1]==0)
it1 = p.erase (it1);
else
it1++;
}
}
I appreciate everyone who can show me what are the code problems and how can I increase my code speed.