• 扩展欧几里得 exGCD


    Elementary Number Theory - Extended Euclid Algorithm

    Time Limit : 1 sec, Memory Limit : 65536 KB 
    Japanese version is here

    Extended Euclid Algorithm


    Given positive integers a and b, find the integer solution (xy) to ax+by=gcd(a,b), where gcd(a,b) is the greatest common divisor of a and b.

    Input

    a b
    

    Two positive integers a and b are given separated by a space in a line.

    Output

    Print two integers x and y separated by a space. If there are several pairs of such x and y, print that pair for which |x|+|y| is the minimal (primarily) and x ≤ y (secondarily).

    Constraints

    • 1 ≤ ab ≤ 109

    Sample Input 1

    4 12
    

    Sample Output 1

    1 0
    

    Sample Input 2

    3 8
    

    Sample Output 2

    3 -1
     1 #include <bits/stdc++.h>
     2 
     3 #define fread_siz 1024
     4 
     5 inline int get_c(void)
     6 {
     7     static char buf[fread_siz];
     8     static char *head = buf + fread_siz;
     9     static char *tail = buf + fread_siz;
    10 
    11     if (head == tail)
    12         fread(head = buf, 1, fread_siz, stdin);
    13 
    14     return *head++;
    15 }
    16 
    17 inline int get_i(void)
    18 {
    19     register int ret = 0;
    20     register int neg = false;
    21     register int bit = get_c();
    22 
    23     for (; bit < 48; bit = get_c())
    24         if (bit == '-')neg ^= true;
    25 
    26     for (; bit > 47; bit = get_c())
    27         ret = ret * 10 + bit - 48;
    28 
    29     return neg ? -ret : ret;
    30 }
    31 
    32 int exgcd(int a, int b, int &x, int &y)
    33 {
    34     if (!b)
    35     {
    36         x = 1;
    37         y = 0;
    38         return a;
    39     }
    40     int ret = exgcd(b, a%b, y, x);
    41     y = y - x * (a / b);
    42     return ret;
    43 }
    44 
    45 signed main(void)
    46 {
    47     int x, y;
    48     int a = get_i();
    49     int b = get_i();
    50     exgcd(a, b, x, y);
    51     printf("%d %d
    ", x, y);
    52 }

    @Author: YouSiki

  • 相关阅读:
    图片处理
    define 常量的定义和读取
    curl
    stream_get_contents 和file_get_content的区别
    php flock 文件锁
    字符串函数
    php 常量
    debug_backtrace()
    pathlib模块替代os.path
    Python中对 文件 的各种骚操作
  • 原文地址:https://www.cnblogs.com/yousiki/p/6227559.html
Copyright © 2020-2023  润新知