Description
给出方程 Ax+By+C=0 的任一介于 −5⋅1018 ~ 5⋅1018 之间的解,不存在则输出 −1
Input
三个整数 A,B,C(−2⋅109≤A,B,C≤2⋅109,A2+B2>0)
Output
如果存在介于 −5⋅1018 ~ 5⋅1018 之间的解则输出任一解,不存在输出 −1
Sample Input
2 5 3
Sample Output
6 -3
Solution
特判 A=0 和 B=0 的情况, A,B≠0 时解一元线性同余方程即可
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=100001;
ll extend_gcd(ll a,ll b,ll &x,ll &y)
{
ll d=a;
if(b)d=extend_gcd(b,a%b,y,x),y-=(a/b)*x;
else x=1,y=0;
return d;
}
int flag;
ll linear(ll a,ll b,ll c)
{
ll x,y;
ll g=extend_gcd(a,c,x,y);
if(b%g)
{
flag=0;
return -1;
}
x=x*(b/g);
ll mod=c/g;
x=(x%mod+mod)%mod;
return x;
}
int main()
{
ll a,b,c;
while(~scanf("%I64d%I64d%I64d",&a,&b,&c))
{
flag=1;
c=-c;
if(b<0)a=-a,b=-b,c=-c;
if(a==0||b==0)
{
if(b==0)
{
if(c%a==0)printf("%I64d 0\n",c/a);
else printf("-1\n");
}
else
{
if(c%b==0)printf("0 %I64d\n",c/b);
else printf("-1\n");
}
continue;
}
ll x=linear(a,c,b);
if(!flag)printf("-1\n");
else
{
ll y=(c-a*x)/b;
printf("%I64d %I64d\n",x,y);
}
}
return 0;
}