0

I want to create a function "f" which calculates the product of two polynomials

a0 +a1X + ···+anX^n and b0+b1X+···+bmX^m

For example, since (1 + x)(3 + 2x^2) = 3 + 3x + 2x^2 + 2x^3,we expect the following resuslt:

f(c(1,1),c(3,0,2))
  [1] 3 3 2 2

I have some idea here:

X^0: a0b0
X^1: a0b1+a1b0
X^2: a0b2+a1b1+a2b0
.
.

So, I have the function like this

A =(a0,a1,....,an),B=(b0,b1,...,bn)
f= function(A,B){
          n=length(A)
          m=length(B)
     for(k in 0:(n+m-2))
       for(j in 0:k)
             {
               C[k+1]=sum(A[j+1]*B[k-j+1])
}
     }

But it doesn't work when I type f(A,B) Did anyone has better idea?

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
梁楷葳
  • 11
  • 6

1 Answers1

3
library(polynom)
p1 <- polynomial(c(1,1))
p2 <- polynomial(c(3,0,2))

p1 * p2
#3 + 3*x + 2*x^2 + 2*x^3 

coefficients(p1 * p2)
#[1] 3 3 2 2

Here is how the multiplication is implemented in the package:

m <- outer(c(1,1), c(3,0,2))
as.vector(tapply(m, row(m) + col(m), sum))
#[1] 3 3 2 2

See the source code of

polynom:::`Ops.polynomial`
Roland
  • 127,288
  • 10
  • 191
  • 288
  • thank you, but we are not allow to use 'polynom' yet – 梁楷葳 Oct 11 '16 at 14:49
  • SO is not a homework service. This is a valid answer to your question. You are under no obligation to accept it, but I prefer to provide this answer for others. – Roland Oct 11 '16 at 14:50
  • @梁楷葳 If you want to ask a homework question on SO they ask that you show some effort (which you did), label it as being for homework, and cite SO in your assignment. So basically you just need to label it as being for homework. – Hack-R Oct 11 '16 at 14:51
  • Yes, I have no issue with your question. But you are asking for better ideas and this is better. Outside of homework, if you had valid reasons not to use a package, you could just extract the code from package polynom. – Roland Oct 11 '16 at 14:56
  • @梁楷葳 Yes, you did. I was just saying that you also need to label it as homework. This gives people context so that they provide relevant answers, etc. – Hack-R Oct 11 '16 at 14:58
  • Thanks for your answer – 梁楷葳 Oct 11 '16 at 15:10