zoukankan      html  css  js  c++  java
  • 扩展欧几里得求ax+by=c的最小正整数解

    第一步 : 给出方程 ax + by = c 。 
    第二步 : 算出 辗转相除法 gcd(a, b) 。 
    第三步 : 运用 扩展欧几里德 ex_gcd(a, b)-》 ax + by = gcd(a,b) 的 一组解(x, y) 。 
    第三步: 根据 c % gcd(a, b) 判断是否 ax + by = c 有解 。 
    第四步 : 根据 ax + by = c 的通解公式 x1 = (x + k * ( b / gcd(a, b) )) * (c / gcd(a, b) 令 b1 = b / gcd(a, b) , 所以 x1 的 最小正整数解 为 : x1 = (x1 % b1 + b1) % b1, 对应的 y1 = (c - a*x1) / b.

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <algorithm>
    #define LL long long
    using namespace std;
     
    void extend_gcd(LL a, LL b, LL& d, LL& x, LL& y)
    {
    if(!b){ d = a; x = 1; y = 0; }
    else { extend_gcd(b, a%b,d, y, x); y -= x*(a/b);}
    }
     
    int main()
    {
    LL a, b, c, d;
    LL x, y, x1, y1;
     
    cin >> a >> b >> c;
     
    extend_gcd(a, b, d, x, y);
    if(c % d != 0)
    printf("Impossible
    ");
    else
    {
    LL b1 = b / d;
    x1 = (x + b1) * (c / d);
    x1 = (x1 % b1 + b1) % b1;
    y1 = (c - a*x1) / b;
     
    printf("x = %lld, y = %lld
    ", x1, y1);
    }
     
    return 0;
    }
    

      

    rush!
  • 相关阅读:
    3.14周末作业
    3.13作业
    文件处理
    字符编码
    基本数据类型总结
    基本数据类型--------------------集合set()
    python入门009
    作业009
    python入门008
    作业008
  • 原文地址:https://www.cnblogs.com/LH2000/p/14371774.html
Copyright © 2011-2022 走看看