7
$\begingroup$

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.

$\endgroup$
4
  • 2
    $\begingroup$ Is this a programming exercise from school, or something you're just wondering about? $\endgroup$ Oct 29, 2015 at 6:50
  • $\begingroup$ 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 $\endgroup$
    – ferrou
    Oct 29, 2015 at 6:51
  • $\begingroup$ 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... $\endgroup$
    – MarcoB
    Oct 29, 2015 at 6:52
  • 3
    $\begingroup$ Is it acceptable to differentiate $n-1$ times and then evaluate the polynomial at $0$? $\endgroup$ Oct 29, 2015 at 7:12

2 Answers 2

6
$\begingroup$

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 *)
$\endgroup$
4
  • 1
    $\begingroup$ 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. $\endgroup$ Oct 29, 2015 at 7:44
  • 1
    $\begingroup$ 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 $\endgroup$
    – Jason B.
    Oct 29, 2015 at 7:48
  • 1
    $\begingroup$ @JasonB I suppose one could propose it as a Mathematica-specific popularity contest on Code Golf $\endgroup$
    – David Z
    Oct 29, 2015 at 11:37
  • 1
    $\begingroup$ How about a prize for answers as short as a Tweet? $\endgroup$ Oct 29, 2015 at 16:54
2
$\begingroup$

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}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.