To implement polynomial operations (polynomial addition, multiplication) in Go, you can create a struct to represent a polynomial and define methods for each operation. Here's an example implementation:
package main
import (
"fmt"
)
type Polynomial struct {
coefficients map[int]float64 // coefficient for each degree
}
func NewPolynomial() *Polynomial {
return &Polynomial{
coefficients: make(map[int]float64),
}
}
func (p *Polynomial) AddTerm(degree int, coefficient float64) {
if coefficient != 0 {
p.coefficients[degree] += coefficient
}
}
func (p *Polynomial) Add(q *Polynomial) *Polynomial {
result := NewPolynomial()
for degree, coefficient := range p.coefficients {
result.AddTerm(degree, coefficient)
}
for degree, coefficient := range q.coefficients {
result.AddTerm(degree, coefficient)
}
return result
}
func (p *Polynomial) Multiply(q *Polynomial) *Polynomial {
result := NewPolynomial()
for degreeP, coefficientP := range p.coefficients {
for degreeQ, coefficientQ := range q.coefficients {
result.AddTerm(degreeP+degreeQ, coefficientP*coefficientQ)
}
}
return result
}
func (p *Polynomial) String() string {
result := ""
for degree, coefficient := range p.coefficients {
result += fmt.Sprintf("%fx^%d + ", coefficient, degree)
}
result = result[:len(result)-3] // remove trailing "+ "
return result
}
func main() {
p := NewPolynomial()
p.AddTerm(2, 3.0) // 3x^2
p.AddTerm(1, -2.0) // -2x
p.AddTerm(0, 1.0) // 1
q := NewPolynomial()
q.AddTerm(1, 4.0) // 4x
q.AddTerm(0, 2.0) // 2
// Addition
sum := p.Add(q)
fmt.Println("Sum:", sum)
// Multiplication
product := p.Multiply(q)
fmt.Println("Product:", product)
}
In this example, the Polynomial
struct represents a polynomial with its coefficients stored in a map. The AddTerm
method is used to add a term (degree and coefficient) to the polynomial. The Add
and Multiply
methods perform polynomial addition and multiplication, respectively. Finally, the String
method is implemented to display the polynomial in a human-readable format.
By running this code, you will get the sum and product of two polynomials.