高次多项式的加法和乘法运算
- 格式:doc
- 大小:76.00 KB
- 文档页数:5
问题:设计程序以实现任意两个高次多项式的加法和乘法运算。
要求:(1)所设计的数据结构应尽可能节省存储空间。
(2)程序的运行时间应尽可能少。
1、模型表示
两个高次多项式相加,要求同类项的系数相加,所得结果作为系数,字母和字母指数不变。两
个高次多项式相乘,要求一个多项式的每项乘与另一个多项式的每一项,并且同底数幂相乘,
底数不变指数相加。如下:
高次多项式1+x2 + x3
高次多项式x+2x2 + x
3
则:
2、算法设计
算法是思想:
算法描述如下:
//polynomial.h 里面的文件
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include
#include
#include
template
class expn_coef {
public:
expn_coef& operator += (expn_coef& s) {
coefficient += s.coefficient;
return *this;
}
expn_coef& operator *= (expn_coef& s) {
coefficient *= s.coefficient;
exponent += s.exponent;
return *this;
}
expn_coef(T t, C c) : exponent(t), coefficient(c) {};
public:
T exponent; //指数
C coefficient; //系数
};
template
std::ostream& operator<<(std::ostream& os, expn_coef
os<<"("<
}
template
inline expn_coef
expn_coef
return r += b;
}
template
inline bool operator < (expn_coef
return a.exponent < b.exponent;
}
template
inline expn_coef
expn_coef
return r *= b;
}
template
class polynomial : public std::list
public:
polynomial() : list(), first(true) {}
polynomial& operator += (polynomial& b);
polynomial& operator *= (polynomial& b);
private:
bool first;
};
template
std::ostream& operator<<(std::ostream& os, polynomial
for(polynomial
os<<*iter<<" ";
return os;
}
template
polynomial
polynomial
return r += b;
}
template
polynomial
polynomial
return r *= b;
}
template
polynomial
if( first ) {
sort();
first = false;
}
if( b.first ) {
b.sort();
first = false;
}
polynomial
polynomial
for( ; ia != end() && ib != b.end(); ) {
if( (*ia).exponent < (*ib).exponent ) ia++;
else if( (*ia).exponent > (*ib).exponent) {
ia = insert(ia, *ib);
ib++;
ia++;
} else {
*ia += *ib;
ia++;
ib++;
}
}
if( ib == b.end() ) return *this;
else
for( ; ib != b.end(); ib++)
push_back(*ib);
return *this;
}
template
polynomial
if( first ) {
sort();
first = false;
}
if( b.first ) {
b.sort();
b.first = false;
}
polynomial
while( !empty() )
pop_back();
polynomial
for( polynomial
temp = store;
for( polynomial
it != temp.end();
it++ ) {
*it *= *ib;
}
*this += temp;
}
return *this;
}
#endif
//main.cpp里面放的文件
#include "polynomial.h"
#include
int main()
{
using namespace std;
polynomial
p1.push_back(expn_coef
p1.push_back(expn_coef
cout<<"第一个多项式方程式(按照(系数,指数)的方式表示):"<
p2.push_back(expn_coef
p2.push_back(expn_coef
p2.push_back(expn_coef
cout<<"第一个多项式方程式(按照(系数,指数)的方式表示):"<
}
结果: