您的位置:首页 > 其它

CodeForces 7 C.Line(一元线性同余方程)

2017-12-23 10:47 369 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: