Find smallest number K such that K % p = 0 and q % K = 0
Last Updated :
22 Jun, 2022
Given two integers p and q, the task is to find the smallest number K such that K % p = 0 and q % K = 0. If no such K is possible then print -1.
Examples:
Input: p = 2, q = 8
Output: 2
2 % 2 = 0 and 8 % 2 = 0
Input: p = 5, q = 14
Output: -1
Approach: In order for K to be possible, q must be divisible by p.
- If q % p = 0 then print p
- Else print -1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getMinVal( int p, int q)
{
if (q % p == 0)
return p;
return -1;
}
int main()
{
int p = 24, q = 48;
cout << getMinVal(p, q);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int getMinVal( int p, int q)
{
if (q % p == 0 )
return p;
return - 1 ;
}
public static void main (String[] args)
{
int p = 24 , q = 48 ;
System.out.println(getMinVal(p, q));
}
}
|
Python3
def getMinVal(p, q):
if q % p = = 0 :
return p
return - 1
p = 24 ; q = 48
print (getMinVal(p, q))
|
C#
using System;
class GFG
{
static int getMinVal( int p, int q)
{
if (q % p == 0)
return p;
return -1;
}
public static void Main ()
{
int p = 24, q = 48;
Console.WriteLine(getMinVal(p, q));
}
}
|
PHP
<?php
function getMinVal( $p , $q )
{
if ( $q % $p == 0)
return $p ;
return -1;
}
$p = 24;
$q = 48;
echo getMinVal( $p , $q );
?>
|
Javascript
<script>
function getMinVal(p, q)
{
if (q % p == 0)
return p;
return -1;
}
let p = 24, q = 48;
document.write(getMinVal(p, q));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...