In: Computer Science
Write a program to multiply two polynomials.
Code needed in Java.
Java Code
import java.util.Scanner;
class Main
{
static int[] mul(int C[], int D[],
int m, int n)
{
int[] p= new int[m + n - 1];
for (int k = 0; k < m + n - 1; k++)
{
p[k] = 0;
}
for (int i = 0; i < m; i++) // Multiply two polynomials term by
term
{
for (int j = 0; j < n; j++)
{
p[i + j] += C[i] * D[j]; // saving the result after Multiply
}
}
return p;
}
static void print(int pi[], int k) // function to print the
polynomial
{
for (int j = 0; j < k; j++)
{
System.out.print(pi[j]);
if (j != 0)
{
System.out.print("x^" + j);
}
if (j != k - 1)
{
System.out.print(" + ");
}
}
}
public static void main(String[] args)
{
int p,i,j;
Scanner s = new Scanner(System.in);
System.out.print("\nEnter the highest degree of the First
polynomial :");
p = s.nextInt(); //input the highest degree of the First
polynomial
int A[] = new int[p+1];
for(i = 0; i<=p; i++)
{ System.out.println("Enter the value for x^"+i);
A[i] = s.nextInt();
}
// The polynomial represents in the format 3 + 2x + 5x^2
System.out.print("\n\nEnter the highest degree of the Second
polynomial :");
p = s.nextInt(); //input the highest degree of the second
polynomial
int B[] = new int[p+1];
for(i = 0; i<=p; i++)
{ System.out.println("Enter the value for x^"+i);
B[i] = s.nextInt();
}
int f = A.length; //finding the size
int k = B.length;
System.out.println("\n\nFirst polynomial is ");
print(A, f); //function call
System.out.println("\n Second polynomial is ");
print(B, k); //function call
int[] l= mul(A,B,f,k);
//function call to multiply
System.out.println("\n\n Product polynomial =");
print(l, f + k - 1);
}
}
Output
(4+8x) * (5+2x) = 20+48x+16x2
(5+10x2+6x3 ) * ( 1+2x+4x2 )