Find minimum x such that (x % k) * (x / k) == n in C++

C++Server Side ProgrammingProgramming

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
raja
Published on 18-Dec-2019 11:37:17
Advertisements