别看!看就是不会!(拓展欧几里德求最小正数解)

 

都说了别看,还看!

好吧,既然点进来了,那就告诉你题意:

给你一个方程,Ax+By+C=0,给你A,B,C;

请找出一组解(x,y),解的要求:

x是所有解中的最小正整数,y就是任意一个整数。

如果存在这样的解,请给出这个解中的x;如果不存在,请输出 -1。

会吗?

Input

 

第一行给你三个数,A,B,C(- 2·1e9≤A,B,C≤ 2·1e9),题目保证A^2 + B^2 > 0。

Output

 

如果存在解,输出一个数x,否则输出-1

Sample Input 1 

2 5 3

Sample Output 1

1

Sample Input 2 

0 2 3

Sample Output 2

-1

Hint

long long 占位符用 %lld,不要用 %I64d。

wa了这么多发终于对了

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<cmath>

const int maxn=1e5+5;
typedef long long ll;
using namespace std;

ll e_gcd(ll a,ll b,ll &x,ll &y) {
	if(b==0) {
		x=1;
		y=0;
		return a;
	}
	ll ans=e_gcd(b,a%b,x,y);
	ll temp=x;
	x=y;
	y=temp-a/b*y;
	return ans;
}

ll cal(ll a,ll b,ll c) {
	ll x,y;
	ll gcd=e_gcd(a,b,x,y);
	if(c%gcd!=0) return -1;
	x*=c/gcd;
	b/=gcd;
	if(b<0) b=-b;
	ll ans=x%b;
	if(ans<=0) ans+=b;
	return ans;
}
int main() {
	ll a, b, c, gcd;
	while(scanf("%lld%lld%lld", &a, &b, &c)!=EOF) {
		c=-c;
		if(b==0) {
			if(c>0&&c%a==0) {
				a=c/a;
				cout<<a<<endl;
			} else {
				cout<<"-1"<<endl;
			}

		} else {
			cout<<cal(a,b,c);
		}
	}
	return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

black-hole6

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值