Find smallest number K such that K % p = 0 and q % K = 0 in C++


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

 Live Demo

#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

Updated on: 18-Dec-2019

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements