crystyxn
crystyxn

Reputation: 1601

Adding two polynomials and displaying the result properly

my code is fairly simple:

    #include <cstdlib>
    #include <iostream>
    #include <string>
    #include <vector>
    #include <numeric>
    #include <cmath>

using namespace std;

int main() {

    int sizeOfPoly1;
    cout<<"Size of first polynomial: ";
    cin>>sizeOfPoly1;
    vector<int> poly1(sizeOfPoly1);
    cout<<"constant =";
    cin>>poly1[0];
    for (int i = 1; i <= (sizeOfPoly1-1); ++i)
    {
        cout<<"Insert x^"<<i<<": ";
        cin>>poly1[i];
    }

    int sizeOfPoly2;
    cout<<"Size of second polynomial: ";
    cin>>sizeOfPoly2;
    vector<int> poly2(sizeOfPoly2);
    cout<<"constant =";
    cin>>poly2[0];
    for (int i = 1; i <= (sizeOfPoly2-1); ++i)
    {
        cout<<"Insert x^"<<i<<": ";
        cin>>poly2[i];
    }


    int sizeOfResult;

    //verifies which polynomial has more elements and makes the result the size of the biggest one
    if (poly1.size() >= poly2.size())  sizeOfResult = poly1.size();
    else sizeOfResult = poly2.size();
    vector<int> result(sizeOfResult);


    for(int i = 0; i<sizeOfResult; ++i) { result[i] = poly1[i] + poly2[i]; }
    cout<<"Sum of the two polynomials: ";

    for(int i = 0; i<sizeOfResult; ++i)
    {
        switch(i){
            case 0:  cout<<result[i]<<" "; break;
            case 1:  cout<<result[i]<<"x"<<" "; break;
            default: cout<<result[i]<<"x^"<<i<<" "; break;
        }

    }


    return 0;
}

What I want to do is to have the user enter their polynomial size and then enter the constant, x^1, x^2 and so on for both of them then return the sum of the two polynomials. This code currently generates something weird like: Sum of the two polynomials: 2 4x 6x^2 8x^3 1772060652x^4 when one polynomial vector has more elements than the other, how can I prevent this output error from happening?

Upvotes: 3

Views: 370

Answers (1)

Slava
Slava

Reputation: 44238

Just make them both the same size and use std::transform:

const auto sizeOfResult = std::max( poly1.size(), poly2.size() );
poly1.resize( sizeOfResult );
poly2.resize( sizeOfResult );

vector<int> result(sizeOfResult);
std::transform( poly1.begin(), poly1.end(), poly2.begin(), result.begin(),
                []( int a, int b ) { return a+b; } );

that's simple solution but has slight overhead. More efficient solution:

auto p = poly1.size() < poly2.size() ? std::tie( poly1, poly2 ) : std::tie( poly2, poly1 );
std::vector<int> result( std::get<1>( p ) );
for( size_t i = 0; i != std::get<0>( p ).size(); ++i )
    result[i] += std::get<0>( p )[i];

live example

Upvotes: 3

Related Questions