Minimum value that divides one number and divisible by other in C++

C++Server Side ProgrammingProgramming

Problem statement

Given two integer p and q, the task is to find the minimum possible number x such that q % x = 0 and x % p = 0. If the conditions aren’t true for any number, then print -1.

Example

If p = 3 and q = 66 then answer is 3 as:
66 % 3 = 0
3 % 3 = 0

Algorithm

  • If a number x satisfies the given condition, then it’s obvious that q will be divided by p i.e. q % p = 0 because x is a multiple of p and q is a multiple of x
  • So the minimum possible value of x will be the GCD of p and q and when q is not divisible by p then no number will satisfy the given condition

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMinValue(int p, int q) {
   if (q % p == 0) {
      return __gcd(p, q);
   }
   return -1;
}
int main() {
   int p = 3;
   int q = 66;
   cout << "Minimum value = " << getMinValue(p, q) << endl;
   return 0;
}

When you compile and execute above program. It generates following output −

Output

Minimum value = 3
raja
Published on 20-Dec-2019 10:17:12
Advertisements