Given two coins of denominations “X” and “Y” respectively, find the largest amount that cannot be obtained using these two coins (assuming infinite supply of coins) followed by the total number of such non obtainable amounts, if no such value exists print “NA”.
Input : X=2, Y=5 Output: Largest amount = 3 Total count = 2 We cannot represent 1 and 3 from infinite supply of given two coins. The largest among these 2 is 3. We can represent all other amounts for example 13 can be represented 2*4 + 5. Input : X=5, Y=10 Output: NA There are infinite number of amounts that cannot be represented by these two coins.
One important observation is, if GCD of X and Y is not one, then all values that can be formed by given two coins are multiples of GCD. For example if X = 4 and Y = 6. Then all values are multiple of 2. So all values that are not multiple of 2, cannot be formed by X and Y. Thus there exist infinitely many values that cannot be formed by 4 and 6, and our answer becomes “NA”.
This general problem for n coins is known as classic Forbenius coin problem.
When the number of coins is two, there is explicit formula if GCD is not 1. The formula is: Largest amount A = (X * Y) - (X + Y) Total amount = (X -1) * (Y - 1) /2
Hence, we can now easily answer the above question by following the below steps:
- Calculate GCD of X and Y
- If GCD is 1 then required largest amount is (X*Y)-(X+Y) and total count is (X-1)*(Y-1)/2
- Else print “NA”
- Make a fair coin from a biased coin
- Coin Change | DP-7
- Probability of getting two consecutive heads after choosing a random coin among two different types of coins
- Expected number of coin flips to get two heads in a row?
- Coin Change | BFS Approach
- Find the player who will win the Coin game
- Probability of getting K heads in N coin tosses
- Count of total Heads and Tails after N flips in a coin
- Minimum moves taken to move coin of each cell to any one cell of Matrix
- Philaland Coin | TCS Mockvita 2020
- Count ways to distribute exactly one coin to each worker
- Probability of not getting two consecutive heads together in N tosses of coin
- Secretary Problem (A Optimal Stopping Problem)
- Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
- The Knight's tour problem | Backtracking-1
- Josephus problem | Set 1 (A O(n) Solution)
- Hungarian Algorithm for Assignment Problem | Set 1 (Introduction)
- The Lazy Caterer's Problem
- Josephus Problem Using Bit Magic
- Maths behind number of paths in matrix problem
Below is a the program based on the same.
Largest Amount = 3 Total Count = 2 NA
This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.