Find minimum positive integer x such that a(x^2) + b(x) + c >= k in C++


Suppose we have four integers a, b, c and k. We have to find the minimum positive value x, such that the following equation satisfies −

𝑎𝑥2+𝑏𝑥+𝑐 ≥𝑘

If a = 3, b = 4, c = 5 and k = 6, then output will be 1

To solve this, we will use the bisection approach. The lower limit will be 0 since x has to be a minimum positive integer.

Example

 Live Demo

#include<iostream>
using namespace std;
int getMinX(int a, int b, int c, int k) {
   int x = INT8_MAX;
   if (k <= c)
      return 0;
   int right = k - c;
   int left = 0;
   while (left <= right) {
      int mid = (left + right) / 2;
      int val = (a * mid * mid) + (b * mid);
      if (val > (k - c)) {
         x = min(x, mid);
         right = mid - 1;
      }
      else if (val < (k - c))
         left = mid + 1;
      else
         return mid;
   }
   return x;
}
int main() {
   int a = 3, b = 2, c = 4, k = 15;
   cout << "Minimum value of x is: " << getMinX(a, b, c, k);
}

Output −

Minimum value of x is: 2

Updated on: 19-Dec-2019

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements