Math, asked by jaypalsinh7713, 1 year ago

Write an algorithm that accepts two polynomials as input and prints the resultant polynomial due to the addition of input polynomials.

Answers

Answered by Akash7766
3
#include<stdio.h> void main() { int poly1[6][2],poly2[6][2],term1,term2,match,proceed,i,j; printf("Enter the number of terms in first polynomial : "); scanf("%d",&term1); printf("Enter the number of terms in second polynomial : "); scanf("%d",&term2); printf("Enter the coeff and expo of the first polynomial:\n"); for(i=0;i<term1;i++) { scanf("%d %d",&poly1[i][0],&poly1[i][1]); } printf("Enter the coeff and expo of the second polynomial:\n"); for(i=0;i<term2;i++) { scanf("%d %d",&poly2[i][0],&poly2[i][1]); } printf("The resultant polynomial after addition :\n"); for(i=0;i<term1;i++) { match=0; for(j=0;j<term2;j++) { if(match==0) if(poly1[i][1]==poly2[j][1]) { printf("%d %d\n",(poly1[i][0]+poly2[j][0]), poly1[i][1]); match=1; } } } for(i=0;i<term1;i++) { proceed=1; for(j=0;j<term2;j++) { if(proceed==1) if(poly1[i][1]!=poly2[j][1]) proceed=1; else proceed=0; } if(proceed==1) printf("%d %d\n",poly1[i][0],poly1[i][1]); } for(i=0;i<term2;i++) { proceed=1; for(j=0;j<term1;j++) { if(proceed==1) if(poly2[i][1]!=poly1[j][1]) proceed=1; else proceed=0; } if(proceed==1) printf("%d %d",poly2[i][0],poly2[i][1]); } getch(); }
Answered by VineetaGara
1

The C++ code to add two given polynomials is :-

1) #include <iostream>  

using namespace std;  

int max(int m, int n) {  return (m > n)? m: n; }  

int *add(int A[], int B[], int m, int n)  

{  

  int size = max(m, n);  

  int *sum = new int[size];  

  for (int i = 0; i<m; i++)  

    sum[i] = A[i];  

  for (int i=0; i<n; i++)  

      sum[i] += B[i];  

  return sum;  

}  

void printPoly(int poly[], int n)  

{  

   for (int i=0; i<n; i++)  

   {  

      cout << poly[i];  

      if (i != 0)  

       cout << "x^" << i ;  

      if (i != n-1)  

      cout << " + ";  

   }  

}  

int main()  

{  

   int A[10] ;

    for(int i=0; i<10;i++)

   cin>>A[i];

   int B[10] ;  

    for(int i=0; i<10;i++)

   cin>>B[i];

   int m = sizeof(A)/sizeof(A[0]);  

   int n = sizeof(B)/sizeof(B[0]);  

 

   cout << "First polynomial is \n";  

   printPoly(A, m);  

   cout << "\nSecond polynomial is \n";  

   printPoly(B, n);  

 

   int *sum = add(A, B, m, n);  

   int size = max(m, n);  

 

   cout << "\nsum polynomial is \n";  

   printPoly(sum, size);  

 

   return 0;  

}

2) The given code works with following algorithm.

a) Create a sum array sum[] of size equal to maximum of 'm' and 'n'

b) Copy A[] to sum[].

c) Traverse array B[] and do following for every element B[i]

         sum[i] = sum[i] + B[i]

d) Return sum[].

Similar questions