Suppose we have two integers P and Q. We have to find smallest number K, such that K mod P = 0 and Q mod K = 0. Otherwise print -1. So if the P and Q are 2 and 8, then K will be 2. As 2 mod 2 = 0, and 8 mode 2 = 0.
In order for K to be possible, Q must be divisible by P. So if P mod Q = 0 then print P otherwise print -1.
Example
#include<iostream>
using namespace std;
int getMinK(int p, int q) {
if (q % p == 0)
return p;
return -1;
}
int main() {
int p = 24, q = 48;
cout << "Minimum value of K is: " << getMinK(p, q);
}Output
Minimum value of K is: 24