Minimum value that divides one number and divisible by other
Last Updated :
24 Jun, 2022
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.
Examples:
Input: p = 3, q = 99
Output: 3
99 % 3 = 0
3 % 3 = 0
Input: p = 2, q = 7
Output: -1
Approach: 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.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minValidNumber( int p, int q)
{
if (q % p == 0)
return __gcd(p, q);
else
return -1;
}
int main()
{
int p = 2, q = 6;
cout << minValidNumber(p, q);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int __gcd( int a, int b)
{
if (a == 0 || b == 0 )
return 0 ;
if (a == b)
return a;
if (a > b)
return __gcd(a - b, b);
return __gcd(a, b - a);
}
static int minValidNumber( int p, int q)
{
if (q % p == 0 )
return __gcd(p, q);
else
return - 1 ;
}
public static void main (String[] args) {
int p = 2 , q = 6 ;
System.out.print(minValidNumber(p, q));
}
}
|
Python3
from math import gcd
def minValidNumber(p, q) :
if (q % p = = 0 ) :
return gcd(p, q)
else :
return - 1
if __name__ = = "__main__" :
p, q = 2 , 6 ;
print (minValidNumber(p, q))
|
C#
using System;
class GFG
{
static int __gcd( int a, int b)
{
if (a == 0 || b == 0)
return 0;
if (a == b)
return a;
if (a > b)
return __gcd(a - b, b);
return __gcd(a, b - a);
}
static int minValidNumber( int p, int q)
{
if (q % p == 0)
return __gcd(p, q);
else
return -1;
}
public static void Main()
{
int p = 2, q = 6;
Console.Write(minValidNumber(p, q));
}
}
|
PHP
<?php
function gcd( $a , $b )
{
if ( $b == 0)
return $a ;
return gcd( $b , $a % $b );
}
function minValidNumber( $p , $q )
{
if ( $q % $p == 0)
return gcd( $p , $q );
else
return -1;
}
$p = 2;
$q = 6;
echo minValidNumber( $p , $q );
?>
|
Javascript
<script>
function __gcd(a, b)
{
if (a == 0 || b == 0)
return 0;
if (a == b)
return a;
if (a > b)
return __gcd(a - b, b);
return __gcd(a, b - a);
}
function minValidNumber(p, q)
{
if (q % p == 0)
return __gcd(p, q);
else
return -1;
}
let p = 2, q = 6;
document.write(minValidNumber(p, q));
</script>
|
Time Complexity: O(logn)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...