Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements