The Wayback Machine - https://web.archive.org/web/20240921020452/https://www.geeksforgeeks.org/integration-in-a-polynomial-for-a-given-value/
Open In App

Integration in a Polynomial for a given value

Last Updated : 04 Jun, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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*(X2) and substituting the value X = 1, we get: 
18 + 6 + 6 + 9 = 39. 
Input: str = “4x3 + 2x2 + 3x”, N = 2 
Output: 27 

Approach: The idea is to use the identity of the integration. For some given function X with the power of N, the integration of this term is given by: 

\int (X^{N}) = \frac{X^{N + 1}}{N + 1}
 

Therefore, the following steps are followed to compute the answer:  


 

  • Get the string.
  • Split the string and perform the integration based on the above formula.
  • Substitute the value of N in the obtained expression.
  • Add all the individual values to get the final integral value.


 

Below is the implementation of the above approach:
 


 

C++

// C++ program to find the integration
// of the given polynomial for the
// value N
 
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
 
// Function to return the integral
// of the given term
double inteTerm(string pTerm, ll val)
{
    // Get the coefficient
    string coeffStr = "";
    int i;
 
    // Loop to iterate through the string
    // and get the coefficient
    for (i = 0; pTerm[i] != 'x'; i++)
        coeffStr.push_back(pTerm[i]);
    ll coeff = atol(coeffStr.c_str());
 
    // Get the Power
    string powStr = "";
 
    // Loop to skip 2 characters for x and ^
    for (i = i + 2; i != pTerm.size(); i++)
        powStr.push_back(pTerm[i]);
    ll power = atol(powStr.c_str());
 
    // Return the computed integral
    return (coeff * pow(val, power + 1))
           / (power + 1);
}
 
// Functionto find the integration
// of the given polynomial for the
// value N
double integrationVal(string poly, int val)
{
    ll ans = 0;
 
    // Using string stream to get the
    // 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 integration
        // of that particular term
        else
            ans = (ans + inteTerm(pTerm, val));
    }
    return ans;
}
 
// Driver code
int main()
{
    string str = "4x^3 + 3x^1 + 2x^2";
    int val = 2;
    cout << integrationVal(str, val);
    return 0;
}

                    

Java

// Java program for the above approach
public class GFG
{
 
  // Function to return the integral
  // of the given term
  static int inteTerm(String pTerm, int val)
  {
 
    // Get the coefficient
    String coeffStr = "";
 
    // Loop to iterate through
    // the string and get the
    // coefficient
    int i = 0;
    while (i < pTerm.length() && pTerm.charAt(i) != 'x')
    {
      coeffStr += pTerm.charAt(i);
      i += 1;
    }
 
    int coeff = Integer.parseInt(coeffStr);
 
    // Get the Power
    String powStr = "";
 
    // Loop to skip 2 characters
    // for x and ^
    int j = i + 2;
    while(j< pTerm.length())
    {
      powStr += (pTerm.charAt(j));
      j += 1;
    }
    int power = Integer.parseInt(powStr);
 
    // Return the computed integral
    return ((coeff * (int)Math.pow(val, power + 1)) / (power + 1));
  }
 
  // Functionto find the integration
  // of the given polynomial for the
  // value N
  static int integrationVal(String poly, int val)
  {
    int ans = 0;
 
    // Using string stream to
    // get the input in tokens
    String[] stSplit = poly.split(" \\+ ");
 
    int i = 0;
    while(i < stSplit.length)
    {
      ans = (ans + inteTerm(stSplit[i], val));
      i += 1;
    }
 
    return ans;
  }
 
  // Driver code
  public static void main(String[] args) {
    String st = "4x^3 + 3x^1 + 2x^2";
    int val = 2;
    System.out.println(integrationVal(st, val));
  }
}
 
// This code is contributed by divyesh072019.

                    

Python3

# Python3 program to find
# the integration of the
# given polynomial for the
# value N
 
# Function to return the integral
# of the given term
def inteTerm(pTerm, val):
 
    # Get the coefficient
    coeffStr = ""
 
    # Loop to iterate through
    # the string and get the
    # coefficient
    i = 0
    while (i < len(pTerm) and
           pTerm[i] != 'x'):
        coeffStr += pTerm[i]
        i += 1
         
    coeff = int(coeffStr)
 
    # Get the Power
    powStr = ""
 
    # Loop to skip 2 characters
    # for x and ^
    j = i + 2
    while j< len(pTerm):
        powStr += (pTerm[j])
        j += 1
    power = int(powStr)
 
    # Return the computed integral
    return ((coeff *
             pow(val,
                 power + 1)) //
            (power + 1))
 
# Functionto find the integration
# of the given polynomial for the
# value N
def integrationVal(poly, val):
 
    ans = 0
 
    # Using string stream to
    # get the input in tokens
    stSplit = poly.split("+")
 
    i = 0
    while i < len(stSplit):
        ans = (ans +
               inteTerm(stSplit[i],
                        val))
        i += 1
 
    return ans
 
# Driver code
if __name__ == "__main__":
 
    st = "4x^3 + 3x^1 + 2x^2"
    val = 2
    print(integrationVal(st, val))
 
# This code is contributed by Chitranayal

                    

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to return the integral
  // of the given term
  static int inteTerm(string pTerm, int val)
  {
 
    // Get the coefficient
    string coeffStr = "";
 
    // Loop to iterate through
    // the string and get the
    // coefficient
    int i = 0;
    while (i < pTerm.Length && pTerm[i] != 'x')
    {
      coeffStr += pTerm[i];
      i += 1;
    }
 
    int coeff = Convert.ToInt32(coeffStr);
 
    // Get the Power
    string powStr = "";
 
    // Loop to skip 2 characters
    // for x and ^
    int j = i + 2;
    while(j< pTerm.Length)
    {
      powStr += (pTerm[j]);
      j += 1;
    }
    int power = Convert.ToInt32(powStr);
 
    // Return the computed integral
    return ((coeff * (int)Math.Pow(val, power + 1)) / (power + 1));
  }
 
  // Functionto find the integration
  // of the given polynomial for the
  // value N
  static int integrationVal(string poly, int val)
  {
    int ans = 0;
 
    // Using string stream to
    // get the input in tokens
    string[] stSplit = poly.Split('+');
 
    int i = 0;
    while(i < stSplit.Length)
    {
      ans = (ans + inteTerm(stSplit[i], val));
      i += 1;
    }
 
    return ans;
  }
 
  // Driver code
  static void Main() {
    string st = "4x^3 + 3x^1 + 2x^2";
    int val = 2;
    Console.WriteLine(integrationVal(st, val));
  }
}
 
// This code is contributed by divyeshrabadiya07.

                    

Javascript

<script>
// Javascript program for the above approach
 
// Function to return the integral
  // of the given term
function inteTerm(pTerm,val)
{
 
    // Get the coefficient
    let coeffStr = "";
  
    // Loop to iterate through
    // the string and get the
    // coefficient
    let i = 0;
    while (i < pTerm.length && pTerm[i] != 'x')
    {
      coeffStr += pTerm[i];
      i += 1;
    }
  
    let coeff = parseInt(coeffStr);
  
    // Get the Power
    let powStr = "";
  
    // Loop to skip 2 characters
    // for x and ^
    let j = i + 2;
    while(j< pTerm.length)
    {
      powStr += (pTerm[j]);
      j += 1;
    }
    let power = parseInt(powStr);
  
    // Return the computed integral
    return Math.floor((coeff * Math.floor(Math.pow(val, power + 1))) / (power + 1));
}
 
// Functionto find the integration
  // of the given polynomial for the
  // value N
function integrationVal(poly,val)
{
    let ans = 0;
  
    // Using string stream to
    // get the input in tokens
    let stSplit = poly.split(" + ");
  
    let i = 0;
    while(i < stSplit.length)
    {
      ans = (ans + inteTerm(stSplit[i], val));
      i += 1;
    }
  
    return ans;
}
 
// Driver code
let st = "4x^3 + 3x^1 + 2x^2";
let val = 2;
document.write(integrationVal(st, val));
 
// This code is contributed by avanitrachhadiya2155
</script>

                    

Output: 
27

 


Similar Reads

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 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
Sgn value of a polynomial
Given a polynomial function f(x) = 1+ a1*x + a2*(x^2) + ... an(x^n). Find the Sgn value of these function, when x is given and all the coefficients also. If value of polynomial greater than 0 Sign = 1 Else If value of polynomial less than 0 Sign = -1 Else if value of polynomial is 0 Sign = 0 Examples: Input: poly[] = [1, 2, 3] x = 1 Output: 1 Expla
6 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
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
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
Solving Homogeneous Recurrence Equations Using Polynomial Reduction
A recurrence relation is an equation that recursively defines a sequence or multidimensional array of values, once one or more initial terms are given; each further term of the sequence or array is defined as a function of the preceding terms. Below are the steps required to solve a recurrence equation using the polynomial reduction method: Form a
8 min read
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
Polynomial Division using Linked List
Given two polynomials P1 and P2 in the form of a singly linked list respectively, the task is to print the quotient and remainder expressions in the form of a singly linked list, obtained by dividing the polynomials P1 by P2. Note: Assume the polynomial is expressed as the higher power of x to the lower power of x(i.e., 0). Examples: Input: P1 = 5
7 min read
Find Characteristic Polynomial of a Square Matrix
In linear algebra, the characteristic polynomial of a square matrix is a polynomial that is invariant under matrix similarity and has the eigenvalues as roots. It has the determinant and the trace of the matrix among its coefficients. The characteristic polynomial of the 3x3 matrix can be calculated using the formula x3 - (Trace of matrix)*x2 + (Su
13 min read
Chromatic Polynomial
The chromatic polynomial of graph G is a polynomial function which defines how many ways we can color a graph with some number of colors. So we can write chromatic polynomial of a graph of n vertices denoted by f(G,λ), where we have λ number of colors. What is Complete Graph?It is a type of graph where every pair of vertices are connected by an uni
5 min read
Chromatic Polynomial(Chromial) For a Tree
In graph theory, a chromatic polynomial is a great tool. It is used to study the coloring properties of graphs. Our primary focus in this article is discussing and deriving the chromatic polynomial for a tree. Chromatic PolynomialsThe chromatic polynomial is nothing but the number of possible ways one is able to color the vertices of a graph with s
3 min read
Horner's Method for Polynomial Evaluation
Given a polynomial of the form cnxn + cn-1xn-1 + cn-2xn-2 + ... + c1x + c0 and a value of x, find the value of polynomial for a given value of x. Here cn, cn-1, .. are integers (may be negative) and n is a positive integer.Input is in the form of an array say poly[] where poly[0] represents coefficient for xn and poly[1] represents coefficient for
6 min read
Pseudo-polynomial Algorithms
What is a pseudo-polynomial algorithm? A pseudo-polynomial algorithm is an algorithm whose worst-case time complexity is polynomial in the numeric value of input (not number of inputs).For example, consider the problem of counting frequencies of all elements in an array of positive numbers. A pseudo-polynomial time solution for this is to first fin
1 min read
Polynomial Time Approximation Scheme
It is a very well known fact that there is no known polynomial time solution for NP Complete problems and these problems occur a lot in real world (See this, this and this for example). So there must be a way to handle them. We have seen algorithms to these problems which are p approximate (For example 2 approximate for Travelling Salesman). Can we
4 min read
Complete the sequence generated by a polynomial
Given a sequence with some of its term, we need to calculate next K term of this sequence. It is given that sequence is generated by some polynomial, however complex that polynomial can be. Notice polynomial is an expression of the following form: P(x) = a0 + a1 x +a2 x^2 + a3 x^3 …….. + an x^nThe given sequence can always be described by a number
10 min read
Program for Derivative of a Polynomial
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^
5 min read
Derivatives of Polynomial Functions
Derivatives are used in Calculus to measure the rate of change of a function with respect to a variable. The use of derivatives is very important in Mathematics. It is used to solve many problems in mathematics like to find out maxima or minima of a function, slope of a function, to tell whether a function is increasing or decreasing. If a function
3 min read
Difference Between Exponential and Polynomial Complexities
Understanding the computational complexity of algorithms is essential in computer science, as it helps determine the feasibility and efficiency of solutions to problems. Two of the most common types of complexities are exponential and polynomial complexities. This article will provided the differences between these two, explaining their characteris
4 min read
Minimize value of x that minimizes value of |a1−x|^c+|a2−x|^c+···+|an−x|^c for value of c as 1 and 2
Given an array arr[] of N elements, the task is to find the value of x that minimizes the value of expression for c = 1. |a1−x|c+|a2−x|c+···+|an−x|c = |a1−x|+|a2−x|+···+|an−x| Examples: Input: arr[] = { 1, 2, 9, 2, 6 } Output: 2Explanation: The best solution is to select x = 2 which produces the sum |1−2| + |2−2| + |9−2| + |2−2| + |6−2| = 12 , whic
9 min read
Minimize value of a given function for any possible value of X
Given an array A[] consisting of N integers(1-based indexing), the task is to find the minimum value of the function [Tex]\sum_{i = 1}^{N}(A[i] - (X + i)) [/Tex] for any possible value of X. Examples: Input: A[] = {1, 2, 3, 4} Output: 0Explanation:Consider the value of X as 0, then the value of the given function is (1 - 1 + 2 - 2 + 3 - 3 + 4 - 4)
6 min read
Why the original value cannot be recovered from a given hash value?
A hash function is a mathematical function that takes input data (also known as the message or pre-image) and produces a fixed-length output called a hash value or digest. One of the main properties of a hash function is that it is designed to be a one-way function, meaning that it is computationally infeasible to recover the original input data fr
10 min read
Check if a given value can be reached from another value in a Circular Queue by K-length jumps
Given integers N, K, A, and B, check if it is possible to reach B from A in a circular queue of integers from 1 to N placed sequentially, by jumps of K length. In each move, If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: N = 5, A = 2, B = 1, K = 2Output: YesExplanation: 2 -&gt; 4 -&gt; 1. Therefore, it is possible to r
9 min read
Queries to increment array elements in a given range by a given value for a given number of times
Given an array, arr[] of N positive integers and M queries of the form {a, b, val, f}. The task is to print the array after performing each query to increment array elements in the range [a, b] by a value val f number of times. Examples: Input: arr[] = {1, 2, 3}, M=3, Q[][] = {{1, 2, 1, 4}, {1, 3, 2, 3}, {2, 3, 4, 5}}Output: 11 32 29Explanation: Af
13 min read
Only integer with positive value in positive negative value in array
Given an array of N integers. In the given, for each positive element 'x' there exist a negative value '-x', except one integer whose negative value is not present. That integer may occur multiple number of time. The task is find that integer. Examples: Input : arr[] = { 1, 8, -6, -1, 6, 8, 8 } Output : 8 All positive elements have an equal negativ
8 min read
Find the maximum possible value of the minimum value of modified array
Given an array of size [Tex]N [/Tex]and a number [Tex]S [/Tex]. The task is to modify the given array such that: The difference between the sum of the array elements before and after modification is exactly equal to S.Modified array elements should be non-negative.The minimum value in the modified array must be maximized.To modify the given array,
9 min read
Check if a Float value is equivalent to an Integer value
Given a floating-point number N, the task is to check if the value of N is equivalent to an integer or not. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: N = 1.5Output: NO Input: N = 1.0Output: YES Approach: The idea is to use the concept of Type Casting. Follow the steps below to solve the problem: Initialize a var
3 min read
Minimize operations to make minimum value of one array greater than maximum value of the other
Given two arrays A[] and B[] consisting of N and M integers, the task is to find the minimum number of operations required to make the minimum element of the array A[] at least the maximum element of the array B[] such that in each operation any array element A[] can be incremented by 1 or any array element B[] can be decremented by 1. Examples: In
6 min read
Practice Tags :