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

本文介绍了一种算法,用于求解形如 Ax+By+C=0 的线性方程的一个解,其中解的范围限定在 -5*10^18 到 5*10^18 之间。特别地,当 A 或 B 为 0 时,提供了特殊情况的处理方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

给出方程Ax+By+C=0的任一介于51018~51018之间的解,不存在则输出1

Input

三个整数A,B,C(2109A,B,C2109,A2+B2>0)

Output

如果存在介于51018~51018之间的解则输出任一解,不存在输出1

Sample Input

2 5 3

Sample Output

6 -3

Solution

特判A=0B=0的情况,A,B0时解一元线性同余方程即可

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值