package poly.visitor; import poly.*; /** * Adds host polynomial to input polynomial. Returns the resulting sum polynomial.
 * Copyright 2000, by Dung X. Nguyen, All rights reserved.
 
* @author Dung X. Nguyen * @since 10/19/2000 */ public class Add implements IVisitor { public static final Add Singleton = new Add (); private Add () { } /** * Uses the helper visitor AddConst to add a constant to the input APolynomial. * @param poly a Constant polynomial * @param rhs the polynomial to be added to poly * @return a APolynomial representing the sum of poly and rhs. */ public Object forConst (ConstPoly poly, Object rhs) { return ((APolynomial)rhs).execute (new AddConst (poly.getLeadCoef()), null); } /** * @param poly a non-constant APolynomial * @param rhs the polynomial to be added to poly * @return a APolynomial representing the sum of poly and rhs. */ public Object forNonConst(NonConstPoly poly, Object rhs) { APolynomial p = (APolynomial)rhs; double pCoef = p.getLeadCoef(); int pDegree = p.getDegree(); double polyCoef = poly.getLeadCoef(); int polyDegree = poly.getDegree(); if (pDegree < polyDegree) { return new NonConstPoly (polyCoef, polyDegree, (APolynomial)poly.getLowerPoly().execute (this, p)); } else if (pDegree == polyDegree) { double coef = polyCoef + pCoef; APolynomial lowerSum = (APolynomial)poly.getLowerPoly().execute(this, p.getLowerPoly()); return 0.0 == coef? // IMPORTANT! lowerSum: new NonConstPoly (coef, polyDegree, lowerSum); } else { return new NonConstPoly (pCoef, pDegree, (APolynomial)poly.execute(this, p.getLowerPoly())); } } }