Friday, January 25, 2013

Procedure to Add Two Polynomials using Arrays

Procedure to add two polynomials

Consider a polynomials
 A=  x4+5x3 +6x2 +1  i.e.,   A=[ 4, 4, 1, 3, 5, 2, 6, 0, 1]
 B= 4x4+2x3 +5x2 +7  i.e.,  A=[ 4, 4, 4, 3, 2, 2, 5, 0, 7]

Vector = array[1 .. 40] of integer;

Procedure AddPolynomial(A,B,C : Vector)
     i, j, k, temp : Integer;
begin
    i=2; j=2; k=2;
        { first while loop represent both polynomials are existing i.e., no
          Polynomial   exhausted }
    while (i<=2*A[1])  and (j<=2*B[1])
    begin
        if A[i]<B[j] then
          begin
             C[k]=B[j];
             C[k+1]=B[j+1];
             j=j+2;
             k=k+2;
          end
        else if A[i]>B[j] then
           begin
             C[k]=A[i];
             C[k+1]=A[i+1];
             i=i+2;
             k=k+2;
           end
        else if A[i]= B[j] then
           begin
               temp= A[i+1]+b[j+1];
               if temp = 0 then
                 begin
                    i=i+2;
                    j=j+2;
                 end
               else
                 begin
                    C[k]=A[i];  { or B[i] powers are equal  }
                    C[k+1]=temp;
                     i=i+2;
                     j=j+2;
                     k=k+2;
                 end
           end
    end

     { first polynomial not exhausted and second polynomial is exhausted }
      while (i<=2*A[1] and j>= 2*B[1])
       begin
           C[k]= A[i];
           C[k+1]= A[i+1]
           i=i+2;
           k=k+2;
       end

     { first polynomial is exhausted and second polynomial is not exhausted }
      while (i>=2*A[1] and j<= 2*B[1])
       begin
           C[k]= B[j];
           C[k+1]= B[j+1]
           j=j+2;
           k=k+2;
       end
     C[1]= k div 2 -1;

End





Program to add polynomial

Program AddTwoPolynomial()
  Vector = array[1 .. 40] of integer;
    A,B,C : Vector;
    i, j, k, temp : Integer;
begin
   write(“Enter first polynomial”);
   read(A[1]);
   for i= 2 to 2*A[1]+1
   read A[i];
   for j= 2 to 2*B[1]+1
   read B[j];
   AddPolynomial(A,B,C);
   write(“the result is “);
   for k=2 to 2*C[1]+1
   write(C[k]);
end

No comments:

Post a Comment