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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 13:10:47