技术控

    今日:58| 主题:57966
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Find the minimum value of m that satisfies ax + by = m and all values after m al

[复制链接]
早起的虫儿被鸟吃 投递于 2016-10-3 18:14:41
139 0
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”.
  Examples:
  1. Input: a = 4, b = 7
  2. Output: 18
  3. Explanation: 18 is the smallest value that can
  4.              can be satisfied by equation 4x + 7y.         
  5.              4*1 + 7*2 = 18

  6.              And after 18 all values are satisifed
  7.              4*3 + 7*1 = 19
  8.              4*5 + 7*0 = 20
  9.              ... and so on.
复制代码
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).  
  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.
  1. // C++ program to find the minimum value of m that satisfies
  2. // ax + by = m and all values after m also satisfy
  3. #include<bits/stdc++.h>
  4. using namespace std;

  5. int findMin(int a, int b)
  6. {
  7.     // If GCD is not 1, then there is no such value,
  8.     // else value is obtained using "a*b-a-b+1'
  9.     return (__gcd(a, b) == 1)? a*b-a-b+1 : -1;
  10. }

  11. // Driver code
  12. int main()
  13. {
  14.     int a = 4, b = 7;
  15.     cout << findMin(a, b) << endl;
  16.     return 0;
  17. }
复制代码
Output:
  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
我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表