# Write a function that returns the coefficient of x^n

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.

• Is this a programming exercise from school, or something you're just wondering about? – J. M.'s discontentment Oct 29 '15 at 6:50
• Nothing, actually, I'm practising by solving exercises but on this one, i'm just completely stuck. From school, it's not a homework, it is in our book – ferrou Oct 29 '15 at 6:51
• Perhaps start by taking a look at the FullForm of a polynomial in Mathematica. You could then try your hand at some pattern matching using Cases... – MarcoB Oct 29 '15 at 6:52
• Is it acceptable to differentiate $n-1$ times and then evaluate the polynomial at $0$? – Patrick Stevens Oct 29 '15 at 7:12

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 *)

• 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 discontentment Oct 29 '15 at 7:44
• 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 7:48
• @JasonB I suppose one could propose it as a Mathematica-specific popularity contest on Code Golf – David Z Oct 29 '15 at 11:37
• How about a prize for answers as short as a Tweet? – David G. Stork Oct 29 '15 at 16:54

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}} *)


Try this:

    Clear[x];
Coefficient[7 x^2 - 3 x^3, x, 2]

(*  7  *)


Have fun!

• OP says "I don't want to use the Coefficient[] function in Mathematica"… – J. M.'s discontentment Oct 29 '15 at 9:08
• @ J. M. Ah, so. Then I wish him a success. – Alexei Boulbitch Oct 29 '15 at 12:09