Polynomial Class Extension
Understand the multiplication of two polynomials.
We'll cover the following...
Problem
Write a program that carries out multiplication of two polynomials.
Coding solution
Here is a solution to the problem above.
Press + to interact
// Polynomial multiplication#include <stdio.h>#include <iostream>const int MAX = 10 ;class poly{private :struct term{int coeff ;int exp ;} t[ MAX ] ;int noofterms ;public :poly( ) ;void polyappend ( int c, int e ) ;void polyadd ( poly &p1, poly &p2 ) ;void polymul ( poly &p1, poly &p2 ) ;void display( ) ;} ;// initializes data members of class polypoly :: poly( ){noofterms = 0 ;for ( int i = 0 ; i < MAX ; i++ ){t[ i ].coeff = 0 ;t[ i ].exp = 0 ;}}// adds the term of polynomial to the array tvoid poly :: polyappend ( int c, int e ){t[ noofterms ].coeff = c ;t[ noofterms ].exp = e ;noofterms++ ;}// displays the polynomial equationvoid poly :: display( ){int flag = 0 ;for ( int i = 0 ; i < noofterms ; i++ ){if ( t[ i ].exp != 0 )std :: cout << t[ i ].coeff << "x^" << t[ i ].exp << " + " ;else{std :: cout << t[ i ].coeff ;flag = 1 ;}}if ( !flag )std :: cout << "\b\b " ;}// add two polynomials p1 and p2void poly :: polyadd ( poly &p1, poly &p2 ){int coeff, exp ;poly p ;int c = p1.noofterms ;int d = p2.noofterms ;for ( int i = 0, j = 0 ; i <= c || j <= d ; ){if ( p1.t[ i ].coeff == 0 && p2.t[ j ].coeff == 0 )break ;if ( p1.t[ i ].exp >= p2.t[ j ].exp ){if ( p1.t[ i ].exp == p2.t[ j ].exp ){coeff = p1.t[ i ].coeff + p2.t[ j ].coeff ;exp = p1.t[ i ].exp ;i++ ;j++ ;}else{coeff = p1.t[ i ].coeff ;exp = p1.t[ i ].exp ;i++ ;}}else{coeff = p2.t[ j ].coeff ;exp = p2.t[ j ].exp ;j++ ;}p.polyappend ( coeff, exp ) ;}*this = p ;}// multiply two polynomials p1 and p2void poly :: polymul ( poly &p1, poly &p2 ){int coeff, exp ;poly t1, t2 ;if ( p1.noofterms != 0 && p2.noofterms != 0 ){for ( int i = 0 ; i < p1.noofterms ; i++ ){poly p ;for ( int j = 0 ; j < p2.noofterms ; j++ ){coeff = p1.t[ i ].coeff * p2.t[ j ].coeff ;exp = p1.t[ i ].exp + p2.t[ j ].exp ;p.polyappend ( coeff, exp ) ;}if ( i != 0 ){t2.polyadd ( t1, p ) ;t1 = t2 ;}elset1 = p ;}*this = t2 ;}}int main( ){poly p1 ;p1.polyappend ( 1, 4 ) ;p1.polyappend ( 2, 3 ) ;p1.polyappend ( 2, 2 ) ;p1.polyappend ( 2, 1 ) ;poly p2 ;p2.polyappend ( 2, 3 ) ;p2.polyappend ( 3, 2 ) ;p2.polyappend ( 4, 1 ) ;poly p3 ;p3.polymul( p1, p2 ) ;std :: cout << std :: endl << "First polynomial: " << std :: endl ;p1.display( ) ;std :: cout << std :: endl << "Second polynomial: " << std :: endl ;p2.display( ) ;std :: cout << std :: endl << "Resultant polynomial: " << std :: endl ;p3.display( ) ;return 0 ;}
Explanation
To carry out the multiplication of two given polynomial equations, the poly
...