VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-root-of-given-non-decreasing-function-between-a-and-b/

⇱ Find the root of given non decreasing function between A and B - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the root of given non decreasing function between A and B

Last Updated : 12 Jul, 2025

Given three numbers a, b, and c that forms a monotonically increasing function of the form a*x2 + b*x + c and two number A and B, the task is to find the root of the function i.e., find the value of x such that where A ? x ? B.
 

Examples:

Input: a = 2, b = -3, c = -2, A = 0, B = 3 
Output: 2.0000 
Explanation: 
f(x) = 2x^2 - 3x - 2 putting the value of x = 2.000 
We get f(2.000) = 2(2.000)^2 - 3(2.000) - 2 = 0
Input: a = 2, b = -3, c = -2, A = -2, B = 1 
Output: No solution

Approach: Below is the graphical representation of any function:

👁 Image


From the above graph, we have,

  1. Whenever f(A)*f(B) ? 0, it means that the graph of the function will cut the x-axis somewhere within that range and signifies that somewhere there is a point which makes the value of the function as 0 and then the graph proceeds to be negative y-axis.
  2. If f(A)*f(B) > 0, it means that in this range [A, B] the y values of f(A) and f(B) both remain positive throughout, so they never cut x-axis.


Therefore, from the above observation, the idea is to use Binary Search to solve this problem. Using the given range of [A, B] as lower and upper bound for the root of the equation, x can be found out by applying binary search on this range. Below are the steps:

  1. Find the middle(say mid) of the range [A, B].
  2. If f(mid)*f(A) ? 0 is true then search space is reduced to [A, mid], because the cut at x-axis has been occurred in this segment.
  3. Else search space is reduced to [mid, B]
  4. The minimum possible value for root is when the high value becomes just smaller than EPS(the smallest value ~10-6) + lower bound value i.e., fabs(high - low) > EPS.
  5. Print the value of the root.


Below is the implementation of the above approach:


Output: 
2.0000

Time Complexity: O(log(B - A)) 
Auxiliary Space: O(1)
 

Comment