Design and implement (i.e write a program) an algorithm that adds two polynomials such a

QUESTION

Design and implement (i.e write a program) an algorithm that adds two polynomials such a

(x*3 + 4×2 -3x + 3) + (6×5 – 2x*2 + 1)

Place the theta value of your algorithm as the first comment in the code. Submit several challenging test cases.

 

SUMMARY

This algorithm finds the value after adds two polynomials and is written in python. The coefficients of the polynomials given are taken in an array and the sum is calculated. These are then displayed as polynomials after calculating the sum.

 

EXPLANATION

The function addpoly takes the coefficients of the two polynomials as arguments in the form of lists. The sum is calculated and the coefficients of this sum are put into a list. printpoly is a method that prints the polynomial from this list.

 

CODE

def addpoly(a,b,m,n):

    size=max(m, n);

    # adds two polynomials

    sum=[0 for i in range(size)]

    # to initialize the sum polynomial with the first polynomial 

    for i in range(0, m, 1):

        sum[i] = a[i]

    for i in range(n):

        sum[i]=sum[i]+b[i]

    return sum

# polynomial coefficeints are taken as an array 

def printpoly(polynomial,n):

    for j in range(n):

        print(polynomial[j],end = "")

        if (j!=0):

            print("x^",j,end="")

        if (j!=n-1):

            print(" + ",end="")

a= [3, -3, 4, 1]

b=[1, 0, -2, 0, 0, 6]

m=len(a)

n=len(b)

print("First polynomial: ")

printpoly(a,m)

print()

print("Second polynomial:")

printpoly(b,n)

print()

s=addpoly(a,b,m,n)

size1=max(m,n)

print("Sum polynomial: ")

printpoly(s,size1)

 

 

OUTPUT

 

Also Read: Create a new Data Frame called Combo that contains every unique combination of characters, bodies, and tires

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *