Check whether the exchange is possible or not
Last Updated :
01 Mar, 2022
Given N types of money denomination in a country as an array arr[]. A person and the shopkeeper can choose notes of each denomination any number of times. The task is to check whether the exchange is possible when the person wants to buy a product worth P from the shop.
Examples:
Input: arr[] = {6, 9}, P = 3
Output: Yes
The person can pay 9 and get 6 in return.
Input: arr[] = {6, 9}, P = 4
Output: No
Approach: In order for the exchange to be possible, P must be divisible by the GCD of all the denominations. So, find the gcd of the array elements and check whether P is divisible by it or not.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible( int arr[], int n, int p)
{
int gcd = 0;
for ( int i = 0; i < n; i++)
gcd = __gcd(gcd, arr[i]);
if (p % gcd == 0)
return true ;
return false ;
}
int main()
{
int arr[] = { 6, 9 };
int n = sizeof (arr) / sizeof ( int );
int p = 3;
if (isPossible(arr, n, p))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static int __gcd( int a, int b)
{
if (b == 0 )
return a;
return __gcd(b, a % b);
}
static boolean isPossible( int []arr,
int n, int p)
{
int gcd = 0 ;
for ( int i = 0 ; i < n; i++)
gcd = __gcd(gcd, arr[i]);
if (p % gcd == 0 )
return true ;
return false ;
}
public static void main (String[] args)
{
int arr[] = { 6 , 9 };
int n = arr.length;
int p = 3 ;
if (isPossible(arr, n, p))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
from math import gcd as __gcd
def isPossible(arr, n, p) :
gcd = 0 ;
for i in range (n) :
gcd = __gcd(gcd, arr[i]);
if (p % gcd = = 0 ) :
return True ;
return False ;
if __name__ = = "__main__" :
arr = [ 6 , 9 ];
n = len (arr);
p = 3 ;
if (isPossible(arr, n, p)) :
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG
{
static int __gcd( int a, int b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
static bool isPossible( int []arr,
int n, int p)
{
int gcd = 0;
for ( int i = 0; i < n; i++)
gcd = __gcd(gcd, arr[i]);
if (p % gcd == 0)
return true ;
return false ;
}
public static void Main (String[] args)
{
int []arr = { 6, 9 };
int n = arr.Length;
int p = 3;
if (isPossible(arr, n, p))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function __gcd(a, b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
function isPossible(arr, n, p)
{
let gcd = 0;
for (let i = 0; i < n; i++)
gcd = __gcd(gcd, arr[i]);
if (p % gcd == 0)
return true ;
return false ;
}
let arr = [ 6, 9 ];
let n = arr.length;
let p = 3;
if (isPossible(arr, n, p))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n * min(a, b)), where a and b are two parameters of _gcd
Auxiliary Space: O(min(a, b))
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...