欧几里得算法

\((a, b)\)为a和b的所有公约数,那么有\((a, b) = (b, a \% b)\)

证明:

\((a, b) = A, (b, a - kb) = B,(a\%b = a - kb,k=[a/b])\)

\(1)\) \(\because\forall x \in A,\)\(x | a\)\(x|b\)

\(\therefore x | (pa + qb),(p,q\in Z)\)

\(\therefore\)\(x|b\)\(x|(a-kb)\)

\(\therefore\forall x \in A\)\(x\in B\),即\(A \sub B\)

\(2)\) \(\because\forall x \in B,\)\(x | (a - kb)\)\(x|b\)

\(\therefore x|[(a - kb) + kb]\)

\(\therefore x|a\)

\(\therefore x|a\)\(x|b\)

\(\therefore\forall x \in B\)\(x\in A\),即\(B \sub A\)

由1)2)得\(A = B\),所以\(max\{A\} = max\{B\}\)

即gcd(a, b) = gcd(b, a % b)

给定n对正整数ai,bi,请你求出每对数的最大公约数。

递归版

#include<iostream>
using namespace std;

int n;

int gcd(int a, int b){
    return b ? gcd(b, a % b) : a;
}

int main(){
    cin >> n;
    
    for(int i = 1; i <= n; i ++){
        int a, b;
        cin >> a >> b;
        
        cout << gcd(a, b) << endl;
    }
    
    return 0;
}

迭代版

#include<iostream>
using namespace std;

int n;

int main(){
    cin >> n;
    
    for(int i = 1; i <= n; i ++){
        int a, b;
        cin >> a >> b;
        
        while(b){
            int t = b;
            b = a % t;
            a = t;
        }
        
        cout << a << endl;
    }
    
    return 0;
}
posted @ 2021-01-07 16:29  yys_c  阅读(102)  评论(0编辑  收藏  举报