LearnFrenzy
Sign in Take a free test

Operator Overloading · Operator Overloading Programs · Question 3

Polynomial addition, multiplication and evaluation in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Write a Polynomial class with +, *, operator() for evaluation at x, and operator<< printing like 3x^2 + 2x + 1.

Solution
main.cpp
#include <iostream>
#include <vector>

class Poly {
    std::vector<int> c_;            // c_[i] is the coefficient of x^i
public:
    Poly(std::vector<int> c) : c_(std::move(c)) {}
    friend Poly operator+(const Poly& a, const Poly& b) {
        std::vector<int> r(std::max(a.c_.size(), b.c_.size()), 0);
        for (std::size_t i = 0; i < a.c_.size(); ++i) r[i] += a.c_[i];
        for (std::size_t i = 0; i < b.c_.size(); ++i) r[i] += b.c_[i];
        return r;
    }
    friend Poly operator*(const Poly& a, const Poly& b) {
        std::vector<int> r(a.c_.size() + b.c_.size() - 1, 0);
        for (std::size_t i = 0; i < a.c_.size(); ++i)
            for (std::size_t j = 0; j < b.c_.size(); ++j) r[i + j] += a.c_[i] * b.c_[j];
        return r;
    }
    long operator()(long x) const {                 // Horner's method
        long v = 0;
        for (auto it = c_.rbegin(); it != c_.rend(); ++it) v = v * x + *it;
        return v;
    }
    friend std::ostream& operator<<(std::ostream& os, const Poly& p) {
        bool first = true;
        for (int i = static_cast<int>(p.c_.size()) - 1; i >= 0; --i) {
            int c = p.c_[i];
            if (c == 0) continue;
            os << (first ? (c < 0 ? "-" : "") : (c < 0 ? " - " : " + "));
            int a = c < 0 ? -c : c;
            if (a != 1 || i == 0) os << a;
            if (i >= 1) os << 'x';
            if (i >= 2) os << '^' << i;
            first = false;
        }
        return first ? os << 0 : os;
    }
};

int main() {
    Poly p({1, 2, 3});          // 3x^2 + 2x + 1
    Poly q({-1, 1});            // x - 1
    std::cout << "p = " << p << "\nq = " << q << "\np + q = " << p + q << "\np * q = " << p * q << '\n';
    std::cout << "p(2) = " << p(2) << ", (p*q)(3) = " << (p * q)(3) << '\n';
    return 0;
}

Output Verified by compiling and running

p = 3x^2 + 2x + 1
q = x - 1
p + q = 3x^2 + 3x
p * q = 3x^3 - x^2 - x - 1
p(2) = 17, (p*q)(3) = 68

operator() makes a polynomial callable like a function, and Horner's method evaluates it in one pass. (p·q)(3) = p(3)·q(3) = 34 × 2 = 68.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links