zoukankan      html  css  js  c++  java
  • 别看!看就是不会!(拓展欧几里德求最小正数解)

    都说了别看,还看!

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

    给你一个方程,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;
    }
  • 相关阅读:
    没有生产管理,只会生产的企业即将被淘汰
    实施一套MES系统需要多少钱?
    MES助力日立电梯提升精细化管理水平
    数据定义
    (CVE-2017-16995)Ubuntu内核提权
    (CVE-2017-7494)Linux Samba远程代码执行
    (CVE-2019-13272)Linux本地提权
    vulnhub 之 dc6
    vulnhub 之 dc 5
    vulnhub 之 dc4
  • 原文地址:https://www.cnblogs.com/Staceyacm/p/10781743.html
Copyright © 2011-2022 走看看