cppadvanced30 minutes

Build a Function to Perform Symbolic Differentiation of Polynomials in C++

Create an advanced C++ function that takes a polynomial expression as a string input and returns its derivative as another string. This function should handle multiple terms, coefficients, exponents, and the variable x correctly, performing symbolic differentiation in standard mathematical notation.

Challenge prompt

Write a function named `differentiatePolynomial` in C++ that accepts a string representing a polynomial (e.g., "3x^3 + 5x^2 - 2x + 7") and returns the derivative as a correctly formatted string (e.g., "9x^2 + 10x - 2"). Your function must support: multiple terms with positive and negative coefficients, terms without explicit coefficients (assumed 1), constant terms, and standard polynomial notations including 'x' and exponentiation with '^'. The output should omit terms with a zero coefficient and simplify correctly (e.g., no x^1, just x, and no x^0 terms).

Guidance

  • Parse the input string to identify terms, coefficients, variables, and exponents.
  • Apply differentiation rules: d/dx [ax^n] = a*n*x^(n-1); constants differentiate to zero.
  • Construct the output string by combining differentiated terms, properly formatted.
  • Handle special cases such as zero coefficients or missing exponent parts.

Hints

  • Split the polynomial string by '+' and '-' signs while preserving signs to extract individual terms.
  • Use string streams or regex to parse coefficients and exponents from each term.
  • Remember to omit terms with a zero coefficient and format terms with exponent 1 as just 'x'.

Starter code

#include <string>

std::string differentiatePolynomial(const std::string& poly) {
    // Your code goes here
    return "";
}

Expected output

For input "3x^3 + 5x^2 - 2x + 7", expected output is "9x^2 + 10x - 2"

Core concepts

string parsingsymbolic computationpolynomial differentiationstring manipulation

Challenge a Friend

Send this duel to someone else and see if they can solve it.