Program for Derivative of a Polynomial

Given a polynomial as string and a value. Evaluate polynomial’s derivative for the given value.
Note: The input format is such that there is a whitespace between a term and the ‘+’ symbol

The derivative of p(x) = ax^n is p'(x) = a*n*x^(n-1)

Also, if p(x) = p1(x) + p2(x)
Here p1 and p2 are polynomials too
p'(x) = p1′(x) + p2′(x)

Input : 3x^3 + 4x^2 + 6x^1 + 89x^0
        2             
Output :58 
Explanation : Derivative of given
polynomial is : 9x^2 + 8x^1 + 6
Now put x = 2
9*4 + 8*2 + 6 = 36 + 16 + 6 = 58  
            
Input : 1x^3
        3
Output : 27

We split the input string into tokens and for each term calculate the derivative separately for each term and add them to get the result.

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find value of derivative of
// a polynomial.
#include <bits/stdc++.h>
using namespace std;
  
long long derivativeTerm(string pTerm, long long val)
{
    // Get coefficient
    string coeffStr = "";
    int i;
    for (i = 0; pTerm[i] != 'x'; i++)
        coeffStr.push_back(pTerm[i]);
    long long coeff = atol(coeffStr.c_str());
  
    // Get Power (Skip 2 characters for x and ^)
    string powStr = "";
    for (i = i + 2; i != pTerm.size(); i++)
        powStr.push_back(pTerm[i]);
    long long power = atol(powStr.c_str());
  
    // For ax^n, we return a(n-1)x^(n-1)
    return coeff * power * pow(val, power - 1);
}
  
long long derivativeVal(string& poly, int val)
{
    long long ans = 0;
  
    // We use istringstream to get input in tokens
    istringstream is(poly);
  
    string pTerm;
    while (is >> pTerm) {
  
        // If the token is equal to '+' then
        // continue with the string
        if (pTerm == "+")
            continue;
  
        // Otherwise find the derivative of that
        // particular term
        else
            ans = (ans + derivativeTerm(pTerm, val));
    }
    return ans;
}
  
// Driver code
int main()
{
    string str = "4x^3 + 3x^1 + 2x^2";
    int val = 2;
    cout << derivativeVal(str, val);
    return 0;
}

chevron_right


Output:

59

This article is contributed by Ankit Jain . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.