The Wayback Machine - https://web.archive.org/web/20240614071511/https://www.geeksforgeeks.org/program-derivative-polynomial/
Open In App

Program for Derivative of a Polynomial

Last Updated : 18 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a polynomial as a string and a value. Evaluate polynomial’s derivative for the given value. 
Note: The input format is such that there is a white space 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. 

C++




// C++ 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 anx^(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;
}


Java




// Java program to find value of derivative of
// a polynomial
import java.io.*;
class GFG 
{
  
  static long derivativeTerm(String pTerm, long val)
  {
  
    // Get coefficient
    String coeffStr = "";
    int i;
    for (i = 0; pTerm.charAt(i) != 'x' ; i++)
    {
      if(pTerm.charAt(i)==' ')
        continue;
      coeffStr += (pTerm.charAt(i));
    }
  
    long coeff = Long.parseLong(coeffStr);
  
    // Get Power (Skip 2 characters for x and ^)
    String powStr = "";  
    for (i = i + 2; i != pTerm.length() && pTerm.charAt(i) != ' '; i++)
    {
      powStr += pTerm.charAt(i);
    }
  
    long power=Long.parseLong(powStr);
  
    // For ax^n, we return a(n)x^(n-1)
    return coeff * power * (long)Math.pow(val, power - 1);
  }
  static long derivativeVal(String poly, int val)
  {
    long ans = 0;
  
    int i = 0;
    String[] stSplit = poly.split("\\+");
    while(i<stSplit.length)
    {
      ans = (ans +derivativeTerm(stSplit[i], val));
      i++;
    }
    return ans;
  }
  
  // Driver code
  public static void main (String[] args) {
  
    String str = "4x^3 + 3x^1 + 2x^2";
    int val = 2;
  
    System.out.println(derivativeVal(str, val));
  }
}
  
// This code is contributed by avanitrachhadiya2155


Python3




# Python3 program to find 
# value of derivative of
# a polynomial.
def derivativeTerm(pTerm, val):
  
    # Get coefficient
    coeffStr = ""
  
    i = 0
    while (i < len(pTerm) and 
           pTerm[i] != 'x'):
        coeffStr += (pTerm[i])
        i += 1
          
    coeff = int(coeffStr)
  
    # Get Power (Skip 2 characters 
    # for x and ^)
    powStr = ""
    j = i + 2
    while j < len(pTerm):
        powStr += (pTerm[j])
        j += 1
     
    power = int(powStr)
  
    # For ax^n, we return 
    # a(n)x^(n-1)
    return (coeff * power * 
            pow(val, power - 1))
  
def derivativeVal(poly, val):
  
    ans = 0
    i = 0
    stSplit = poly.split("+") 
     
    while (i < len(stSplit)):      
        ans = (ans + 
               derivativeTerm(stSplit[i], 
                              val))
        i += 1
  
    return ans
  
# Driver code
if __name__ == "__main__":
  
    st = "4x^3 + 3x^1 + 2x^2"
    val = 2    
    print(derivativeVal(st, val))
  
# This code is contributed by Chitranayal


C#




// C# program to find value of derivative of
// a polynomial
using System;
  
class GFG{
  
static long derivativeTerm(string pTerm, long val)
{
  
    // Get coefficient
    string coeffStr = "";
    int i;
      
    for(i = 0; pTerm[i] != 'x'; i++)
    {
        if (pTerm[i] == ' ')
            continue;
              
        coeffStr += (pTerm[i]);
    }
      
    long coeff = long.Parse(coeffStr);
      
    // Get Power (Skip 2 characters for x and ^)
    string powStr = "";  
    for(i = i + 2; 
        i != pTerm.Length && pTerm[i] != ' '; 
        i++)
    {
        powStr += pTerm[i];
    }
      
    long power = long.Parse(powStr);
      
    // For ax^n, we return a(n)x^(n-1)
    return coeff * power * (long)Math.Pow(val, power - 1);
}
  
static long derivativeVal(string poly, int val)
{
    long ans = 0;
      
    int i = 0;
    String[] stSplit = poly.Split("+");
      
    while (i < stSplit.Length)
    {
        ans = (ans +derivativeTerm(stSplit[i], val));
        i++;
    }
    return ans;
}
  
// Driver code
static public void Main()
{
    String str = "4x^3 + 3x^1 + 2x^2";
    int val = 2;
      
    Console.WriteLine(derivativeVal(str, val));
}
}
  
// This code is contributed by rag2127


Javascript




<script>
// Javascript program to find value of derivative of
// a polynomial
  
function derivativeTerm( pTerm,val)
{
    // Get coefficient
    let coeffStr = "";
    let i;
    for (i = 0; pTerm[i] != 'x' ; i++)
    {
      if(pTerm[i]==' ')
        continue;
      coeffStr += (pTerm[i]);
    }
   
    let coeff = parseInt(coeffStr);
   
    // Get Power (Skip 2 characters for x and ^)
    let powStr = ""; 
    for (i = i + 2; i != pTerm.length && pTerm[i] != ' '; i++)
    {
      powStr += pTerm[i];
    }
   
    let power=parseInt(powStr);
   
    // For ax^n, we return a(n)x^(n-1)
    return coeff * power * Math.pow(val, power - 1);
}
  
function derivativeVal(poly,val)
{
    let ans = 0;
   
    let i = 0;
    let stSplit = poly.split("+");
    while(i<stSplit.length)
    {
      ans = (ans +derivativeTerm(stSplit[i], val));
      i++;
    }
    return ans;
}
  
 // Driver code
let str = "4x^3 + 3x^1 + 2x^2";
let val = 2;
document.write(derivativeVal(str, val));
  
  
// This code is contributed by ab2127
</script>


Output

59

Time Complexity: O(n), where n is the number of terms in the polynomial.
Auxiliary Space: O(1)

 



Previous Article
Next Article

Similar Reads

Partial derivative of a polynomial using Doubly Linked List
Given a 2-variable polynomial represented by a doubly linked list, the task is to find the partial derivative of a polynomial stored in the doubly-linked list. Examples: Input: P(x, y) = 2(x^3 y^4) + 3(x^5 y^7) + 1(x^2 y^6)Output:Partial derivatives w.r.t. x: 6(x^2 y^4) + 15(x^4 y^7) + 2(x^1 y^6)Partial derivatives w.r.t. y: 24(x^2 y^3) + 105(x^4 y
15+ min read
Program to find the indefinite Integration of the given Polynomial
Given a polynomial string str, the task is to integrate the given string and print the string after integrating it. Note: The input format is such that there is a whitespace between a term and the ‘+’ symbol. Examples: Input: str = "4X3 + 3X1 + 2X2" Output: X4 + (3/2)X2 + (2/3)X3 + C Input: str = "5X3 + 7X1 + 2X2 + 1X0" Output: (5/4)X4 + (7/2)X2 +
8 min read
Program to differentiate the given Polynomial
Given polynomial string str, the task is to differentiate the given string and print the string after differentiating it. Note: The input format is such that there is a white space between a term and the ‘+’, ’-’ symbolExamples: Input: str = "4X3 + 3X1 + 2X2" Output: "12X2 + 3X0 + 4X1" Explanation: The derivative of p(x) = A*XN is p'(x) = A * N * X
8 min read
Program to find the value of P(N + r) for a polynomial of a degree N such that P(i) = 1 for 1 &le; i &le; N and P(N + 1) = a
Given three positive integers N, R, and A and a polynomial P(X) of degree N, P(i) = 1 for 1 ? i ? N and the value of P(N + 1) is A, the task is to find the value of the P(N + R). Examples: Input: N = 1, R = 3, A = 2Output: 4Explanation:The equation of the given polynomial is P(x) = x. Therefore, the value of P(N + R) = P(4) = 4. Input: N = 2, R = 3
7 min read
Fast Fourier Transformation for polynomial multiplication
Given two polynomial A(x) and B(x), find the product C(x) = A(x)*B(x). There is already an O([Tex]n^2 [/Tex]) naive approach to solve this problem. here. This approach uses the coefficient form of the polynomial to calculate the product.A coefficient representation of a polynomial [Tex]A(x)=\sum_{j=0}^{n-1}a_jx^j [/Tex]is a = a0, a1, ..., an-1. Exa
13 min read
Iterative Fast Fourier Transformation for polynomial multiplication
Given two polynomials, A(x) and B(x), find the product C(x) = A(x)*B(x). In the previous post, we discussed the recursive approach to solve this problem which has O(nlogn) complexity. Examples: Input : A[] = {9, -10, 7, 6} B[] = {-5, 4, 0, -2} Output : C(x) = [Tex]-12x^6 -14x^5 +44x^4 -20x^3 - 75x^2 +86x -45[/Tex] In real-life applications such as
12 min read
Finding nth term of any Polynomial Sequence
Given a few terms of a sequence, we are often asked to find the expression for the nth term of this sequence. While there is a multitude of ways to do this, In this article, we discuss an algorithmic approach which will give the correct answer for any polynomial expression. Note that this method fails for trigonometric, exponential or other transce
4 min read
Minimize the sum of roots of a given polynomial
Given an array whose elements represent the coefficients of a polynomial of degree n, if the polynomial has a degree n then the array will have n+1 elements (one extra for the constant of a polynomial). Swap some elements of the array and print the resulting array such that the sum of the roots of the given polynomial is as minimum as possible irre
15+ min read
Python | Finding Solutions of a Polynomial Equation
Given a quadratic equation, the task is to find the possible solutions to it. Examples: Input : enter the coef of x2 : 1 enter the coef of x : 2 enter the constant : 1 Output : the value for x is -1.0 Input : enter the coef of x2 : 2 enter the coef of x : 3 enter the constant : 2 Output : x1 = -3+5.656854249492381i/4 and x2 = -3-5.656854249492381i/
2 min read
Integration in a Polynomial for a given value
Given string str which represents a polynomial and a number N, the task is to integrate this polynomial with respect to X at the given value N. Examples: Input: str = "90x4 + 24x3 + 18x2 + 18x", N = 1. Output: 39 Explanation: Given, dy/dx = 90*(X4) + 24* (X3) + 18* (X2) + 18*(X). On integrating this equation, we get 18*(X5) + 6*(X4) + 6*(X3) + 9*(X
7 min read
Practice Tags :