C. Line
Description
A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist.
Input
The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0.
Output
If the required point exists, output its coordinates, otherwise output -1.
Sample Input
2 5 3
6 -3
//
题目大意:
给方程Ax + By + C = 0. 其中A,B,C为已知, 求x,y。
分析与总结:
拓展欧几里得算法的模板题。这个算法在数论书或者网上都可以找到。
该算法求出线性方程Ax + By = gcd(A, B);
然后,这个方程可进行转换:
Ax + By = gcd(A, B)
=> Ax + By = -C/z, 其中-C/z = gcd(A, B)
=> Ax*z + By*z = C.
其中x, y可以通过拓展欧几里得算法求出,
然后,我们只需要求出z, 而z = -C/gcd(A,B);
所以, 最终答案x = x*(-C/gcd(A,B)) , y = y*(-C/gcd(A,B));
//具体算法解释看:http://blog.csdn.net/zhjchengfeng5/article/details/7786595
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define ll long long
#define INF 5*1e18
using namespace std;
void gcd(ll a,ll b,ll& d,ll& x,ll& y)
{
if(!b)
{
d=a;
x=1;
y=0;
}
else
{
gcd(b,a%b,d,y,x);
y-=x*(a/b);
}
}
int main()
{
ll a,b,c,d,x,y;
while(scanf("%lld%lld%lld",&a,&b,&c)!=EOF)
{
gcd(a,b,d,x,y);
if(c%d!=0)
printf("-1\n");
else
printf("%lld %lld\n",-x*(c/d),-y*(c/d));
}
return 0;
}
//标准模板
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define ll long long
#define INF 5*1e18
using namespace std;
ll gcd(ll a,ll b,ll& x,ll& y)
{
if(!b)
{
x=1;
y=0;
return a;
}
ll ans=gcd(b,a%b,x,y);
int temp=x;
x=y;
y=temp-a/b*y;
return ans;
}
int main()
{
ll a,b,c,d,x,y;
while(scanf("%lld%lld%lld",&a,&b,&c)!=EOF)
{
d=gcd(a,b,x,y);
if(c%d!=0)
printf("-1\n");
else
printf("%lld %lld\n",-x*(c/d),-y*(c/d));
}
return 0;
}