Problem Description
Mirko has given up on the difficult coach job and switched to food tasting instead. Having skipped breakfast like a professional connoisseur, he is visiting a Croatian cured meat festival. The most renowned cook at the festival, Marijan Bajs, has prepared N equal sausages which need to be distributed to M tasters such that each taster gets a precisely equal amount. He will use his trusted knife to cut them into pieces.
In order to elegantly divide the sausages, the number of cuts splitting individual sausages must be as small as possible. For instance, if there are two sausages and six tasters (the first test case below), it is sufficient to split each sausage into three equal parts, making a total of four cuts. On the other hand, if there are three sausages and four tasters (the second test case below), one possibility is cutting off three quarters of each sausage. Those larger parts will each go to one of the tasrers, while the fourth taster will get the three smaller pieces (quarters) left over.
Mirko wants to try the famous sausages, so he volunteered to help Bajs. Help them calculate the minimum total number of cuts needed to carry out the desired division.
Input
There are multiple test cases. Please process till EOF.
The first line of input contains two positive integers, N and M (1 ≤ N, M ≤ 100), the number of sausages and tasters, respectively.
Output
The first and only line of output must contain the required minimum number of cuts.
Sample Input
2 6
3 4
6 2
Sample Output
4
3
0
解题思路
题意是 将n根香肠 平均分给 m个人,求最少要切几刀.
一上来我的思路就是递归写…但是一直WA,可能是某个方面没处理好…无奈最后只好换种思路了ORZ…
我们不妨将n根香肠先连起来,再平均分,那么平均分给m个人的话,就应该切m-1刀,
然后再遍历这m-1刀,找出那些本来就是两根的连接处,那么这刀就不需要我们切,扣去这刀就行了.
参考代码
#include <iostream>
using namespace std;
int main()
{
int n, m;
while (cin >> n >> m){
int ans = m-1;
for (int i = 1;i < m;i++)
if (n*i % m == 0) ans--;
cout << ans << endl;
}
return 0;
}