zoukankan      html  css  js  c++  java
  • 欧几里得算法

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

    证明:

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

    (1)) (ecauseforall x in A,)(x | a)(x|b)

    ( herefore x | (pa + qb),(p,qin Z))

    ( herefore)(x|b)(x|(a-kb))

    ( hereforeforall x in A)(xin B),即(A sub B)

    (2)) (ecauseforall x in B,)(x | (a - kb))(x|b)

    ( herefore x|[(a - kb) + kb])

    ( herefore x|a)

    ( herefore x|a)(x|b)

    ( hereforeforall x in B)(xin 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;
    }
    
  • 相关阅读:
    drf—— 序列化组件
    drf—— RESTful API规范
    drf——APIView及其内部函数/类的源码分析
    drf—— drf的安装和使用
    226翻转二叉树
    51,N皇后
    557反转字符串中的单词III
    17.电话号码的字母组合
    459重复的子字符串
    419递增子序列
  • 原文地址:https://www.cnblogs.com/tomori/p/14247116.html
Copyright © 2011-2022 走看看