7

Write a function C[p_, x_, n_] that returns the coefficient of $x^n$ in the polynomial equation.

C[p_, x_, n_] := ...

If we call C[7 x^2 - 3 x^3, x, 2], the output should be 7. I don't want to use the Coefficient[] function in Mathematica, I just want to understand how it is done.

mmal
  • 3,508
  • 2
  • 18
  • 38
ferrou
  • 125
  • 4

2 Answers2

6

Just do what SeriesCoefficient does yourself

coeff[polynomial_, variable_, order_] := 
 D[polynomial, {variable, order}]/(order!) /. variable -> 0

coeff[7 x^2 - 3 x^3, x, 2]
(* 7 *)

coeff[347 x^19 - 7 x^2 - 3 x^3, x, 19]
(* 347 *)
Jason B.
  • 68,381
  • 3
  • 139
  • 286
  • 1
    If one wanted to be cruel, he could have posted a contour integral method for extracting the coefficient… and then there's the method that uses FFT. – J. M.'s missing motivation Oct 29 '15 at 07:44
  • 1
    There should be a badge or something for the most convoluted answer to a question. Or the most inscrutable - some of the answers here are so compact I have no clue what they are doing – Jason B. Oct 29 '15 at 07:48
  • 1
    @JasonB I suppose one could propose it as a Mathematica-specific popularity contest on [codegolf.SE] – David Z Oct 29 '15 at 11:37
  • 1
    How about a prize for answers as short as a Tweet? – David G. Stork Oct 29 '15 at 16:54
2

Here's a pattern-matching version (not tested carefully since the question is already answered):

coeff[poly_, var_, orders_List] := Cases[Expand@poly, a_. var^# :> a] & /@ orders

Usage: orders is a list of the wanted orders, so

poly = (x + 5) (x - 1) (x^2 + y); Expand@poly
coeff[poly, x, {3, 1, 8, 4}]
(* -5 x^2 + 4 x^3 + x^4 - 5 y + 4 x y + x^2 y *)
(* {{4}, {4 y}, {}, {1}} *)
march
  • 23,399
  • 2
  • 44
  • 100