Given two positive integers ‘a’ and ‘b’ that represent coefficients in equation ax + by = m. Find the minimum value of m that satisfies the equation for any positive integer values of x and y. And after this minimum value, the equation is satisfied by all (greater) values of m. If no such minimum value exists, return “-1”.
您需要 登录 才可以下载或查看，没有帐号？立即注册
This is a variation of Frobenius coin problem. In Frobenius coin problem, we need to find the largest number that can not be represented using two coins. The largest amount for coins with denominations as ‘a’ and ‘b’ is a*b – (a+b). 复制代码
- Input: a = 4, b = 7
- Output: 18
- Explanation: 18 is the smallest value that can
- can be satisfied by equation 4x + 7y.
- 4*1 + 7*2 = 18
- And after 18 all values are satisifed
- 4*3 + 7*1 = 19
- 4*5 + 7*0 = 20
- ... and so on.
This question is a direct implementation of a theorem – “Chicken McNugget Theorem”. It states that if the two numbers, a and b, are co-prime, then there exists an minimum integer m, above which ax + by = m is true for any positive numbers x and y.
- // C++ program to find the minimum value of m that satisfies
- // ax + by = m and all values after m also satisfy
- using namespace std;
- int findMin(int a, int b)
- // If GCD is not 1, then there is no such value,
- // else value is obtained using "a*b-a-b+1'
- return (__gcd(a, b) == 1)? a*b-a-b+1 : -1;
- // Driver code
- int main()
- int a = 4, b = 7;
- cout << findMin(a, b) << endl;
- return 0;
This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.orgor mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
上一篇：The best way to map a Java 1.8 Optional entity attribute with JPA and Hibernate
下一篇：Building Your Startup With PHP: Choosing and Configuring Production Hosting