# Thread: Trouble with creating Method and functionality for multiplying a polynomial

1. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Trouble with creating Method and functionality for multiplying a polynomial

Hello i am trying to work out how to multiply two polynomials entered from keyboard input together. Have got the addition working, and multiplying by a constant. But am unable to get the multiplication method and functionality right.
You can see my attempt at multiplication under multiply by a monomial code.

Any help is appreciated.

thanks

Java Code:
```import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;

public class Polynomial
{
private int TOLERANCE = 0;

/******************  the  Monomial (inner) class   ********************************/

private class Monomial
{
private DecimalFormat precision = new DecimalFormat("#.####");
private int deg;     // degree of polynomial
private int coeff; // coefficients
private Monomial next; // Pointer to next term

public Monomial(int coeff, int deg, Monomial next)
{
this.coeff = coeff;  	//coefficient
this.deg = deg;  		// Degree
this.next = next;		// Pointer
}
public String toString()
{
String form = precision.format(Math.abs(coeff));

if(deg == 0) return form ;
else
if(deg == 1) return form + "x";
else
return form +"x^" + deg;
}
public boolean equals(Monomial mono)
{
return coeff == mono.coeff && deg == mono.deg;
}

}

//*********************************************************************************************

public Polynomial()
{
}

/***************************************************************************
*  Adds a new term into the polynomial, assuming that the polynomial
*  is sorted in order from smallest to largest exponent.
**************************************************************************/
public void addTerm(int coeff, int deg)
{
if( Math.abs(coeff) < TOLERANCE ) return;

{
return;
}

Monomial prev = null;

while( cur != null && deg > cur.deg)
{
prev = cur;
cur = cur.next;
}
if( cur == null || deg != cur.deg )
prev.next = new Monomial(coeff, deg, cur);
else
{
cur.coeff += coeff;
if( Math.abs(cur.coeff) < TOLERANCE )
if(prev != null)
prev.next = cur.next;
else
}
}

public String toString()
{
StringBuffer sb = new StringBuffer();

for(Monomial tmp = head; tmp != null; tmp = tmp.next)
if(tmp.coeff < 0 )
sb.append(" - " + tmp.toString());
else
sb.append(" + " + tmp.toString());

return sb.toString();
}

//*********************************************************************************************

/*********************************************************************************************

*  Return the degree of this polynomial

**********************************************************************************************/

//*********************************************************************************************/

/*********************************************************************************************
*  Multiplies Polynomial 1 to Polynomial 2
*  The method does not change the original polynomial.
**********************************************************************************************/

//*********************************************************************************************/

/*********************************************************************************************
*  Adds Polynomial 1 to Polynomial 2
*  The method does not change the original polynomial.
**********************************************************************************************/
{
Polynomial res = clone();

for(Monomial tmp = poly.head; tmp != null; tmp = tmp.next)

return res;
}

public Polynomial clone()
{
Polynomial res = new Polynomial();

for(Monomial tmp = head; tmp != null; tmp = tmp.next)

return res;
}

public boolean equals(Polynomial poly)
{

while(tmp1 != null && tmp2 != null)
{
if( !tmp1.equals(tmp2) ) return false;
tmp1 = tmp1.next;
tmp2 = tmp2.next;
}
return true;
}

//*********************************************************************************************/

/*********************************************************************************************
*  Multiplies by a Constant
*  The method does not change the original polynomial.
**********************************************************************************************/

public Polynomial multiply(int num)
{
Polynomial res = clone();

for(Monomial tmp = res.head; tmp != null; tmp = tmp.next)
tmp.coeff *= num;

return res;
}

//*********************************************************************************************/

/*********************************************************************************************
*  Returns a new polynomial that is the derivative of this polynomial.
**********************************************************************************************/
public Polynomial diff()
{
Polynomial res = new Polynomial();

for(Monomial tmp = head; tmp != null; tmp = tmp.next)
{
if(tmp.deg != 0)
res.addTerm(tmp.coeff * tmp.deg, tmp.deg - 1 );
}

return res;
}

//*********************************************************************************************/

/*********************************************************************************************
*  Returns a new polynomial that is the result of Monomial times polynomial.
**  The method does not change the original polynomial.
**********************************************************************************************/
/*
public Polynomial times(Polynomial poly)
{
{
Polynomial result = new Polynomial();

for(Monomial tmp2 = poly.head; tmp2 != null; tmp2 = tmp2.next)

for(Monomial tmp = head; tmp != null; tmp = tmp.next)

while(tmp != null && tmp2 != null)
{
result.addTerm(tmp.coeff * tmp2.coeff, tmp.deg + tmp2.deg);
tmp = tmp.next;
tmp2 = tmp2.next;
}
return result;

}

}
*/

//*********************************************************************************************/

/*********************************************************************************************
*  Driver Program to Test Polynomial Class
**********************************************************************************************/

public static void main(String[] args)

{

//---------------- Code to chose between keyboard input or file input------------------------

System.out.println("If you would like you enter the polynomial via a text file 'Polyinput.txt' PRESS

1. ");
System.out.println("If you would like you enter the polynomial via the keyboard, PRESS ANY OTHER

INTEGER... ");
Scanner inputquestion=new Scanner(System.in);
System.out.print("Enter Option: "); // Prompts for selection choice
int option=inputquestion.nextInt(); // Stores input in option

if (option == 1) // if loop to jump into read from text file
{

String content = new String();
String name = new String();
File file = new File("polyinput.txt");

try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNext()) {
name = sc.next();
content = sc.nextLine();

}

sc.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}

Iterator<String> i = list.iterator();
while (i.hasNext()) {
System.out.println(name + i.next() + "\n");

}

} //------------ End if to enter input text file code---------------------------------------

else  //--------------start of else for keyboard input--------------------------------------
{

//------- Code to Prompt for Polynomial 1

-----------------------------------------------------------------

Polynomial polynomial1 = new Polynomial();
System.out.println( );
System.out.println( );
System.out.println("Enter first Polynomial");
System.out.println("(Enter Zero (0) as Exponent value to move to second Polynomial");
System.out.println( );

//Insert do while loop exponent not equal 0
int ExponentTest = 1;
do {

Scanner inputCoefficent=new Scanner(System.in);
System.out.print("Enter Coefficient: "); // Prompts for coefficent
int Coefficient=inputCoefficent.nextInt(); // Stores coefficent in coefficent
Scanner inputExponent=new Scanner(System.in);
System.out.print("Enter Exponent: "); // Prompts for Exponent
int Exponent=inputExponent.nextInt(); // Stores Exponent in Exponent

if (Exponent < 1)
{
ExponentTest = 0;
}

} while (ExponentTest > 0);
// ------ end do while loop ---------------

System.out.println( );
System.out.println( " Entered Polynomial is: " + polynomial1 );

//----------------------------------------------------------------------------------------------------------

//----------- Code to Prompt for Polynomial 2 -----------------------------------------------------------------

Polynomial polynomial2 = new Polynomial();
System.out.println( );
System.out.println( );
System.out.println("Enter second Polynomial");
System.out.println("(Enter Zero (0) as Exponent value to complete Polynomial");
System.out.println( );

//Insert do while loop exponent not equal 0
int ExponentTest2 = 1;
do {

Scanner inputCoefficent=new Scanner(System.in);
System.out.print("Enter Coefficient: "); // Prompts for coefficent
int Coefficient=inputCoefficent.nextInt(); // Stores coefficent in coefficent
Scanner inputExponent=new Scanner(System.in);
System.out.print("Enter Exponent: "); // Prompts for Exponent
int Exponent=inputExponent.nextInt(); // Stores Exponent in Exponent

if (Exponent < 1)
{
ExponentTest2 = 0;
}

} while (ExponentTest2 > 0);
// ------ end do while loop ---------------

System.out.println( );
System.out.println( " Entered Polynomial is: " + polynomial2 );

//----------------------------------------------------------------------------------------------------------

//------- Code to Prompt for Monomial (ax^k) to multiply both Polynomials by---------------------------------

Polynomial monomial1 = new Polynomial();
System.out.println( );
System.out.println( );
System.out.println("Enter details for the Monomial equation");
Scanner inputMonomial=new Scanner(System.in);
System.out.print("Enter Coefficent: "); //Prompts for Coefficient
int num1=inputMonomial.nextInt(); // Stores Coefficient in num1
System.out.print("Enter Exponent: "); // Prompts for Exponent
int num2=inputMonomial.nextInt(); //Stores Exponenent in num2
monomial1.addTerm(num1, num2); // Creates the Monomial equation

System.out.println();
System.out.println( "Monomial: " );
System.out.println( monomial1 );
System.out.println( );

//----------------------------------------------------------------------------------------------------

//------- Code to Prompt for constant to multiply by and then reads in the constant and stores in Constant1

System.out.println("Enter integer to be used as the constant");
Scanner inputConstant=new Scanner(System.in);
System.out.print("Enter Constant: "); // Prompts for constant
int Constant1=inputConstant.nextInt(); // Stores Constant in Constant1

System.out.println( "Constant used to multiply polynomials: " );
System.out.println( Constant1 );
System.out.println( );

//----------------------------------------------------------------------------------------------------------

//------------------------ Returns display for operations onto the screen-----------------------------------

System.out.println( );
System.out.println( "Degree of Polynomial 1 ("+ polynomial1 + "): " /*+ polynomial1.degree()*/);

System.out.println( );
System.out.println( "Degree of Polynomial 2 ("+ polynomial2 + "): " );

System.out.println( );
System.out.println( "Multiply Polynomial 1 ("+ polynomial1 + ") by Polynomial 2 ("+ polynomial2 + "): " );

System.out.println( );
System.out.println( "Multiply Polynomial 1 ("+ polynomial1 + ") by Monomial ("+ monomial1 + "): " );
System.out.println( monomial1 + " * " + polynomial1 + " = " + MultiplyMonomialResult1 );
System.out.println( );

System.out.println( );
System.out.println( "Multiply Polynomial 2 ("+ polynomial2 + ") by Monomial ("+ monomial1 + "): " );
System.out.println( monomial1 + " * " + polynomial2 + " = " + MultiplyMonomialResult2 );
System.out.println( );

System.out.println( );
System.out.println( "Polynomial 1 (" + polynomial1 + ") plus Polynomial 2 (" + polynomial2 + "): " );
System.out.println( polynomial1 );
System.out.println( polynomial2 );
System.out.println( "=" );
System.out.println( );

System.out.println( "multiply Polynomial 1 ("+ polynomial1 + ") by constant entered into console (ie " +

Constant1 + "): " );
Polynomial MultiplyConstant1 = polynomial1.multiply(Constant1);
System.out.println( Constant1 + " * " + polynomial1 + " = " + MultiplyConstant1 );
System.out.println( );

System.out.println( "multiply Polynomial 2 ("+ polynomial2 + ") by constant entered into console (ie " +

Constant1 + "): " );
Polynomial MultiplyConstant2 = polynomial2.multiply(Constant1);
System.out.println( Constant1 + " * " + polynomial2 + " = " + MultiplyConstant2 );
System.out.println( );

System.out.println( "Derivative of Polynomial 1: " );
Polynomial diffresult1 = polynomial1.diff();
System.out.println( "Polynomial 1: " + polynomial1 );
System.out.println( "Derivative =  " + diffresult1 );
System.out.println( );

System.out.println( "Derivative of Polynomial 2" );
Polynomial diffresult2 = polynomial2.diff();
System.out.println( "Polynomial 2: " + polynomial2 );
System.out.println( "Derivative =  " + diffresult2 );
System.out.println( );

//-------------------------------End Screen output of operations for keyboard entry-------------------------

} // End of else for keyboard input.------------------------------------------------------------------------

}
}```  Reply With Quote

2. ## Re: Trouble with creating Method and functionality for multiplying a polynomial

Keep your question to the point. I don't think no one has that much time to read ~500 lines.

Point out those lines or methods that may be troubling you.....Don't quote your whole project  Reply With Quote

3. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Re: Trouble with creating Method and functionality for multiplying a polynomial Originally Posted by gauravfzd Keep your question to the point. I don't think no one has that much time to read ~500 lines.

Point out those lines or methods that may be troubling you.....Don't quote your whole project

Thank you

i'm having problem with this code
Java Code:
``` /*********************************************************************************************
*  Returns a new polynomial that is the result of Monomial times polynomial.
**  The method does not change the original polynomial.
**********************************************************************************************/
/*
public Polynomial times(Polynomial poly)
{
{
Polynomial result = new Polynomial();

for(Monomial tmp2 = poly.head; tmp2 != null; tmp2 = tmp2.next)

for(Monomial tmp = head; tmp != null; tmp = tmp.next)

while(tmp != null && tmp2 != null)
{
result.addTerm(tmp.coeff * tmp2.coeff, tmp.deg + tmp2.deg);
tmp = tmp.next;
tmp2 = tmp2.next;
}
return result;

}

}
*/```
and then referencing it with line
Java Code:
`Polynomial MultiplyMonomialResult1 = polynomial1.times(monomial1);`
in the driver program  Reply With Quote

4. ## Re: Trouble with creating Method and functionality for multiplying a polynomial

If you can multiply a polynomial by a constant, you can also multiply a polynomial by a monomial (a polynomial with one term); simply add the exponent of the monomial to the result of the multiplication. You claimed you can also add two poynomials, so your problem is solved ;-)

kind regards,

Jos  Reply With Quote

5. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Re: Trouble with creating Method and functionality for multiplying a polynomial

This is what i'm calling to multiply by constant:

Polynomial MultiplyConstant1 = polynomial1.multiply(Constant1);

and this is the code that performs the multiplication

/************************************************** *******************************************
* Multiplies by a Constant
* The method does not change the original polynomial.
************************************************** ********************************************/

public Polynomial multiply(int num)
{
Polynomial res = clone();

for(Monomial tmp = res.head; tmp != null; tmp = tmp.next)
tmp.coeff *= num;

return res;
}

how do i change that to accept the monomial?

thanks  Reply With Quote

6. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Re: Trouble with creating Method and functionality for multiplying a polynomial

i have changed the above code to be:

public Polynomial times(Polynomial poly)
{
Polynomial res = clone();

for(Monomial tmp = res.head; tmp != null; tmp = tmp.next)

return res;
}

but i get the error

Polynomial.java:314: operator * cannot be applied to int,Polynomial.Monomial
^
1 error

??  Reply With Quote

7. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Re: Trouble with creating Method and functionality for multiplying a polynomial

ok i needed to put in poly.head.coeff to get rid of the error it ran but now only the coefficients are multiplying

Multiply Polynomial 2 ( + 9 + 5x^2 + 3x^4) by Monomial ( + 5x^2):
+ 5x^2 * + 9 + 5x^2 + 3x^4 = + 45 + 25x^2 + 15x^4  Reply With Quote

8. ## Re: Trouble with creating Method and functionality for multiplying a polynomial

Do it by hand, multiply, say, 1+2*x+x^2 by the monomial 3*x; first multiply by a constant value 3, giving 3+6*x+3*x^2 (you claimed you could already do that and next increment the exponents by 1 (the exponent of the monomial), giving: 3*x+6*x^2+x^3; voila. Multiplying two polynomials is multiplying a polynomial by a bunch of monomials and adding the results (you alo claimed you can do addition, so all you have to implement is a bit of fiddling with the exponents; see above for an example).

kind regards,

Jos  Reply With Quote

9. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Re: Trouble with creating Method and functionality for multiplying a polynomial

ok i've got it kind of working. it works for the exponents, but now its doubling the coefficients.

eg
+ 5x^2 * + 7 + 2x + 3x^4 = + 70x^2 + 20x^3 + 30x^6

instead of what it should be which is: 35x^2 + 10x^3 + 15x^6

here the code i implemented:

public Polynomial times(Polynomial poly)
{
Polynomial res = clone();

for(Monomial tmp = res.head; tmp != null; tmp = tmp.next)

return res;
}  Reply With Quote

10. ## Re: Trouble with creating Method and functionality for multiplying a polynomial

System.out.println( ... ) is your friend; sprinkle in that statement and print out every relevant (intermediate) result and check it.

kind regards,

Jos  Reply With Quote

11. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Re: Trouble with creating Method and functionality for multiplying a polynomial

thanks heaps, i have the multiplication by a monomial sorted, am just working polynomial by polynomial. it only multiplying by first term in the polynomial at the moment  Reply With Quote

12. ## Re: Trouble with creating Method and functionality for multiplying a polynomial Originally Posted by bradoz thanks heaps, i have the multiplication by a monomial sorted, am just working polynomial by polynomial. it only multiplying by first term in the polynomial at the moment
It's not too difficult: if you want to multiply a polynomial p(x) by, say, a polynomial x^2+2*x+1 you have to multipy your polynomial p(x) by three monomials, x^2, 2*x and 1; add the three intermediate results and voila.

kind regards,

Jos  Reply With Quote

13. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Re: Trouble with creating Method and functionality for multiplying a polynomial

how do i split that second polynomial into the 3 monomials? and then how do i determine how many monomials i'll need? the second polynomial added could have a dozen terms etc  Reply With Quote

14. ## Re: Trouble with creating Method and functionality for multiplying a polynomial

Isn't a Polynomial just a list of Monomials?

kind regards,

Jos  Reply With Quote

15. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Re: Trouble with creating Method and functionality for multiplying a polynomial

Yes though i am having trouble accessing that list.

here is the code i am using:

polynomial 1 used to get mutliplied by the first term in polynomial 2 and not by each term in polynomial 2.

Below is my code:

/************************************************** *******************************************
* Multiplies Polynomial 1 to Polynomial 2
* The method does not change the original polynomial.
************************************************** ********************************************/

public Polynomial multiply(Polynomial poly)
{
Polynomial res = clone();

for(Monomial tmp2 = poly.head; tmp2 != null; tmp2 = tmp2.next) //-------- LINE B

for(Monomial tmp = res.head; tmp != null; tmp = tmp.next)
double num = 0.5;
for(Monomial tmp = res.head; tmp != null; tmp = tmp.next)
tmp.coeff *= num;
// Polynomial MultiplicationResult = res.add(res2); // add result of two multiplcations together
// res + poly
return res;

}

Now this is the result i'm getting

Multiply Polynomial 1 by Polynomial 2:
+ 6x^7 + 3x^4 + 5x^2 + 8 *
+ 5x^7 + 9
=
+ 300x^21 + 150x^18 + 250x^16 + 400x^14

(If i remove that LINE B from the code above thats when i would get the result of 5x^7 * 6x^7 + 3x^4 + 5x^2 + 8)

thanks  Reply With Quote

16. ## Re: Trouble with creating Method and functionality for multiplying a polynomial

You only need one loop in your multiply method; something like this (pseudo code):

Java Code:
```Polynomial mul(Polynomial q) { // multiply this polynomial by polynomial q
Polynomial res= null; // result of this*q
for (Monomial term : q) { // for each term of polynomial q
if (res == null) res= mul(this, term); // multiply this by a monomial
else res= add(res, res.clone().mul(this, term); // ditto but add to previous result
}
return res;
}```
Note that 'res' is used for the sum of the product of this polynomial and the terms of polynomial q.

kind regards,

Jos  Reply With Quote

17. Member Join Date
Mar 2012
Posts
16
Rep Power
0

## Re: Trouble with creating Method and functionality for multiplying a polynomial

Thanks heaps, i got it sorted :)  Reply With Quote

18. ## Re: Trouble with creating Method and functionality for multiplying a polynomial

Well done; are you going to implement polynmial division now? ;-)

kind regards,

Jos  Reply With Quote

linked list, method, multiplication, polynomials 