Candy Distribution(扩展欧几里得)

Candy Distribution(扩展欧几里得)

Kids like candies, so much that they start beating each other if the candies are not fairly distributed. So on your next party, you better start thinking before you buy the candies.
If there are K kids, we of course need K⋅X candies for a fair distribution, where X is a positive natural number. But we learned that always at least one kid looses one candy, so better be prepared with exactly one spare candy, resulting in (K⋅X)+1 candies.
Usually, the candies are packed into bags with a fixed number of candies C. We will buy some of these bags so that the above constraints are fulfilled.
Input
The first line gives the number of test cases t (0<t<100). Each test case is specified by two integers K and C on a single line, where K is the number of kids and C the number of candies in one bag (1≤K,C≤109). As you money is limited, you will never buy more than 109 candy bags.
Output
For each test case, print one line. If there is no such number of candy bugs to fulfill the above constraints, print “IMPOSSIBLE” instead. Otherwise print the number of candy bags, you want to buy. If there is more than one solution, any will do.
**Sample Input **
5
10 5
10 7
1337 23
123454321 42
999999937 142857133
Sample Output
IMPOSSIBLE
3
872
14696943
166666655

解题思路

题意就是给出一个人数k,给出一袋糖果的数量c,要求买的糖果总数比人数多1,问买几代。设买x袋,也就是cxmod k=1;可以写成,cx+ky=1;根据扩展欧几里得就可以求出来x,但是这题特例,如果c=1,根据方程求出来的是1(因为11=1),而根据题意是k+1;如果k=1,根据方程求出来x=0,(因为0*c+1=1),根据题意如果c>1,x=2就成立(比如c=3,可以给孩子两颗留一颗)

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
typedef long long ll;

ll exgcd(ll a,ll b,ll &x,ll &y)
{
	if(!b)
	{
		x=1;
		y=0;
		return a;
	}
	ll r=exgcd(b,a%b,x,y);
	ll t=y;
	y=x-a/b*y;
	x=t;
	return r;//扩展欧几里得 
}

int main()
{
	ll t;
	scanf("%lld",&t);
	while(t--)
	{
		ll k,c,x,y;
		scanf("%lld %lld",&k,&c);
		if(c==1) 
		{
			printf("%lld\n",k+1);//特判 
			continue;
		}
		if(k==1&&c>1)
		{
			printf("1\n");//特判 
			continue;
		}
		ll d=exgcd(c,k,x,y);
		if(d!=1) printf("IMPOSSIBLE\n");
		else 
		printf("%lld\n",(x%k+k)%k);
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值