- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 x such that (x % k) * (x / k) == n in C++
Given two positive integers n and k, and we have to find the positive integer x, such that (x % k)*(x / k) is same as n. So if the n and k are 4 and 6 respectively, then the output will be 10. So (10 % 6) * (10 / 6) = 4.
As we know that the value of x % k will be in range [1 to k – 1] (0 is not included) Here we will find possible integer in the range that divides n and hence the given equation becomes: x = (n * k) / (x % k) + (x % k)
Example
#include<iostream> using namespace std; int minValue(int x, int y){ return (x > y)?y:x; } int getX(int n, int k) { int x = INT_MAX; for (int rem = k - 1; rem > 0; rem--) { if (n % rem == 0) x = minValue(x, rem + (n / rem) * k); } return x; } int main() { int n = 4, k = 6; cout << "The minimum value of x: " << getX(n, k); }
Output
The minimum value of x: 10
Advertisements
To Continue Learning Please Login
Login with Google