Combine like terms in a polynomial equation

220 views Asked by At

Not homework or anything, just personal interests on coding, learning it by myself currently. Found this question interesting online.

Think if we have a list of number that's

1 2 2 4 3 6 4 2 5 4

that equals to 1x^2+2^4+3^6+4^2+5^4 How can I combine the numbers when they have the same exponent? which will become 5x^2+6x^4+3x^6

I think we can use a linked list in this case? But I don't really know use this data structure

Or anything other way to solve this kind of problem?

Prefer examples in C++ or Java

1

There are 1 answers

0
Minh On

You can do it like this:

#include <iostream>
#include <vector>
#include <map>
 
int main()
{
    std::vector<int> nums{1, 2, 2, 4, 3, 6, 4, 2, 5, 4};
    std::map<int, int> exponent_occurences;
    for (unsigned int i = 1; i < nums.size(); i += 2)
        exponent_occurences[nums.at(i)] += nums.at(i - 1);
    for (auto& [exponent, coef]: exponent_occurences)
        std::cout << coef << "x^" << exponent << std::endl;
    return 0;
}