Open In App

Program to differentiate the given Polynomial

Improve
Improve
Like Article
Like
Save
Share
Report

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 ‘+’, ’-’ symbol
Examples: 

Input: str = “4X3 + 3X1 + 2X2” 
Output: “12X2 + 3X0 + 4X1” 
Explanation: 
The derivative of p(x) = A*XN is p'(x) = A * N * XN – 1
Input: str = “5X4 + 6X2 + 5X2” 
Output: “20X3 + 12X1 + 10X1”  

Approach: The idea is to observe that when the given equation consists of multiple polynomials 

p(x) = p1(x) + p2(x)

, the differentiation of the given polynomial 

p'(x) = p1'(x) + p2'(x)

. And, it is known that the derivative of 

p(x) = AX^N

is 

p'(x) = A*N*X^{N - 1}

Therefore, we split the given string and differentiate every term in it. 
Below is the implementation of the above approach:
 

C++

// C++ program to differentiate the
// given polynomial
 
#include "bits/stdc++.h"
#define MOD (1e9 + 7);
using ll = int64_t;
using ull = uint64_t;
#define ll long long
using namespace std;
 
// Function to differentiate the
// given term
string diffTerm(string pTerm)
{
    // Get the coefficient
    string coeffStr = "", S = "";
    int i;
 
    // Loop to get the coefficient
    for (i = 0; pTerm[i] != 'x'; i++)
        coeffStr.push_back(pTerm[i]);
 
    long long coeff
        = atol(coeffStr.c_str());
 
    // Loop to get the power of each term
    string powStr = "";
    for (i = i + 2; i != pTerm.size(); i++)
        powStr.push_back(pTerm[i]);
 
    long long power
        = atol(powStr.c_str());
    string a, b;
 
    // Converting the value
    // to the string
    ostringstream str1, str2;
 
    // For ax^n, we find (n)*a*x^(n-1)
    coeff = coeff * power;
    str1 << coeff;
    a = str1.str();
    power--;
    str2 << power;
    b = str2.str();
    S += a + "X^" + b;
 
    return S;
}
 
// Function to differentiate the
// given polynomial
string diffstr(string& poly)
{
 
    // We use istringstream to get
    // the input in tokens
    istringstream is(poly);
 
    string pTerm, S = "";
 
    // For every token, compute the
    // differentiation
    while (is >> pTerm) {
 
        // If the token is equal to
        // '+', '-' then
        // continue with the string
        if (pTerm == "+") {
            S += " + ";
            continue;
        }
 
        if (pTerm == "-") {
            S += " - ";
            continue;
        }
 
        // Otherwise find the differentiation
        // of that particular term
        else
            S += diffTerm(pTerm);
    }
    return S;
}
 
// Driver code
int main()
{
    string str = "5x^4 + 6x^2 + 5x^2";
    cout << diffstr(str);
    return 0;
}

                    

Java

import java.util.Scanner;
import java.util.StringTokenizer;
 
public class DifferentiatePolynomial {
  static String diffTerm(String pTerm) {
    // Get the coefficient
    String coeffStr = "", S = "";
    int i;
 
    // Loop to get the coefficient
    for (i = 0; pTerm.charAt(i) != 'x'; i++) {
      coeffStr = coeffStr + pTerm.charAt(i);
    }
 
    long coeff = Long.parseLong(coeffStr);
 
    // Loop to get the power of each term
    String powStr = "";
    for (i = i + 2; i != pTerm.length(); i++) {
      powStr = powStr + pTerm.charAt(i);
    }
 
    long power = Long.parseLong(powStr);
    String a, b;
 
    // Converting the value
    // to the string
    StringBuilder str1 = new StringBuilder();
    StringBuilder str2 = new StringBuilder();
 
    // For ax^n, we find (n)*a*x^(n-1)
    coeff = coeff * power;
    str1.append(Long.toString(coeff));
    a = str1.toString();
    power--;
    str2.append(Long.toString(power));
    b = str2.toString();
    S = S + a + "X^" + b;
 
    return S;
  }
 
  static String diffstr(String poly) {
    String pTerm, S = "";
    StringTokenizer st = new StringTokenizer(poly, " +");
 
    // For every token, compute the differentiation
    while (st.hasMoreTokens()) {
      pTerm = st.nextToken();
 
      // If the token is equal to '+', '-' then continue with the string
      if (pTerm.equals("+")) {
        S = S + " + ";
        continue;
      }
 
      if (pTerm.equals("-")) {
        S = S + " - ";
        continue;
      }
 
      // Otherwise find the differentiation of that particular term
      else {
        S = S + diffTerm(pTerm)+"+";
      }
    }
 
    return S;
  }
 
  public static void main(String[] args) {
    String poly = "5x^4+6x^2+5x^2";
    String ans = diffstr(poly);
    System.out.println(ans.substring(0,ans.length()-1));
 
  }
}

                    

Python3

# Python3 program to differentiate
# the given polynomial
MOD = (1e9 + 7)
 
# Function to differentiate
# the given term
def diffTerm(pTerm):
 
    # Get the coefficient
    coeffStr = ""
    S = ""
 
    # Loop to get the
    # coefficient
    i = 0
    while (i < len(pTerm) and
           pTerm[i] != 'x'):
        coeffStr += (pTerm[i])
        i += 1
 
    coeff = int(coeffStr)
 
    # Loop to get the power
    # of each term
    powStr = ""
    j = i + 2
    while j < len(pTerm):
        powStr += (pTerm[j])
        j += 1
 
    power = int(powStr)
 
    # For ax^n, we find
    # (n)*a*x^(n-1)
    coeff = coeff * power
    a = str(coeff)
    power -= 1
    b = str(power)
    S += a + "X^" + b
 
    return S
 
# Function to differentiate
# the given polynomial
def diffstr(poly):
 
    pTerm = poly.split(" ")
    S = ""
     
    for i in range(len(pTerm)):
 
        # If the token is equal to
        # '+', '-' then
        # continue with the string
        if (pTerm[i] == "+"):
            S += " + "
            continue
 
        if (pTerm[i] == "-"):
            S += " - "
            continue
 
        # Otherwise find the differentiation
        # of that particular term
        else:
            S += diffTerm(pTerm[i])
 
    return S
 
# Driver code
if __name__ == "__main__":
 
    st = "5x^4 + 6x^2 + 5x^2"
    print(diffstr(st))
 
# This code is contributed by Chitranayal

                    

C#

// C# program to differentiate the
// given polynomial
 
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Function to differentiate the
    // given term
    static string diffTerm(string pTerm)
    {
        // Get the coefficient
        string coeffStr = "", S = "";
        int i;
 
        // Loop to get the coefficient
        for (i = 0; pTerm[i] != 'x'; i++)
            coeffStr += (pTerm[i]);
 
        long coeff = Convert.ToInt64(coeffStr);
 
        // Loop to get the power of each term
        string powStr = "";
        for (i = i + 2; i != pTerm.Length; i++)
            powStr += (pTerm[i]);
 
        long power = Convert.ToInt64(powStr);
        string a, b;
 
         
 
        // For ax^n, we find (n)*a*x^(n-1)
        coeff = coeff * power;
        a = Convert.ToString(coeff);
        power--;
        b = Convert.ToString(power);
        S += a + "X^" + b;
 
        return S;
    }
 
    // Function to differentiate the
    // given polynomial
    static string diffstr(string poly)
    {
 
        // We use istringstream to get
        // the input in tokens
        string[] is1 = poly.Split(" ");
 
        string S = "";
 
        // For every token, compute the
        // differentiation
        foreach(string pTerm in is1)
        {
 
            // If the token is equal to
            // '+', '-' then
            // continue with the string
            if (pTerm == "+") {
                S += " + ";
                continue;
            }
 
            if (pTerm == "-") {
                S += " - ";
                continue;
            }
 
            // Otherwise find the differentiation
            // of that particular term
            else
                S += diffTerm(pTerm);
        }
        return S;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        string str = "5x^4 + 6x^2 + 5x^2";
        Console.WriteLine(diffstr(str));
    }
}
 
// This code is contributed by phasing17.

                    

Javascript

// JS program to differentiate the
// given polynomial
 
let MOD = (1e9 + 7);
 
// Function to differentiate the
// given term
function diffTerm(pTerm)
{
    // Get the coefficient
    let coeffStr = "", S = "";
    let i;
 
    // Loop to get the coefficient
    for (i = 0; pTerm[i] != 'x'; i++)
        coeffStr += (pTerm[i]);
 
    let coeff
        = parseInt(coeffStr);
 
    // Loop to get the power of each term
    let powStr = "";
    for (i = i + 2; i != pTerm.length; i++)
        powStr += (pTerm[i]);
 
    let power
        = parseInt(powStr);
    let a = "";
    let b = "";
 
    // Converting the value
    // to the string
    let str1, str2;
 
    // For ax^n, we find (n)*a*x^(n-1)
    coeff = coeff * power;
    str1 = coeff;
    a = str1;
    power--;
    str2 = power;
    b = str2;
    S += a + "X^" + b;
 
    return S;
}
 
// Function to differentiate the
// given polynomial
function diffstr( poly)
{
 
    // We use istringstream to get
    // the input in tokens
    let is = poly.split(" ");
 
    let pTerm = "", S = "";
 
    // For every token, compute the
    // differentiation
    for (pTerm of is)
   {
        // If the token is equal to
        // '+', '-' then
        // continue with the string
        if (pTerm == "+") {
            S += " + ";
            continue;
        }
 
        if (pTerm == "-") {
            S += " - ";
            continue;
        }
 
        // Otherwise find the differentiation
        // of that particular term
        else
            S += diffTerm(pTerm);
    }
    return S;
}
 
// Driver code
let str = "5x^4 + 6x^2 + 5x^2";
console.log(diffstr(str));
 
 
// This code is contributed by phasing17

                    

Output: 
20X^3 + 12X^1 + 10X^1

 


Last Updated : 17 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads