Programming math - polynomial class



How to write templated polynomial class

I would like to have overloaded operators like
+
-(unary,binary)
* Here we can have school multiplication or Karatsuba multiplication
/
%
== , != (relational , comparing two polynomials)
>>,<< (stream , reading and writing)

It will be good to have
parseString(string s) and toString() methods

Polynomial evaluation - Horner's rule

How should I store coefficients ?
In vector or in array

What constructors and destructor should look like


I found C struct with operations but how to rewrite it to C++

Here is link to this struct

https://pastebin.com/75byrXHW





If you search the internet you will find several examples of templated class C++ code for polynomials.
I love peoples who have nothing to write about given topic but answering it anyway
hej kujon, you're just asking people to do your assignment without showing a shred of evidence that you've tried to write any code yourself.

If you don't know how many coefficients you will need, you either need to have an array with a maximum supported size, or you use a dynamic array/vector. The default option in C++ normally is "use vector".

Maybe tackle Polynomial evaluation / Horner's rule last, since that's probably the hardest to calculate.

Start simple, say with == and !=. Then move onto +.

You can represent your polynomial as a sequence of coefficients, e.g.
6 x^3 - 5 x + 3 could be represented as [6, 0, -5, 3].

So checking for equality would just be first checking the that the sizes of two polynomial's are the same (assuming no leading zero coefficients), and then testing for equality element by element. Try it.

Your constructor's argument could be a vector of coefficients. If you do it correctly, you probably won't even need to define a destructor. You might need to simplify your polynomial if the user enters a polynomial where the highest power(s) have zeroes as their coefficients.

e.g.
1
2
3
std::vector<int> simplify(const std::vector<int>& coeffs) {

}


but I'm getting ahead of myself, I wouldn't even worry about that yet.

Write test cases as you build functionality with expected results.

e.g.
1
2
3
4
5
6
7
8
// Test ==
Assert(Polynomial({1, 2, 3}) == Polynomial({1, 2, 3}));
Assert(Polynomial({1, 2, 3}) != Polynomial({1}));

// Test +
Assert(Polynomial({1}) + Polynomial({2}) == Polynomial({3}));
Assert(Polynomial({1, 2}) + Polynomial({1}) == Polynomial({1, 3}));
...


It's not clear what you'd want the "/" operator to do. I mean, if you are just dealing with scalars, then that's trivial, but are you trying to support Polynominal / Polynomial? The answer isn't necessarily a polynomial. If you want "/" to only give the "whole polynomial" and % to only give the remainder, then it could work.
Last edited on
Registered users can post here. Sign in or register to post.