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;
    }
    
  • 相关阅读:
    阅读任务
    自我介绍
    学习总结
    第十二周课程总结
    第十一周课程总结
    第十周课程总结
    第九周课程总结&实验报告(七)
    第四周课程总结&实验报告
    第3周Java编程总结
    学习总结
  • 原文地址:https://www.cnblogs.com/tomori/p/14247116.html
Copyright © 2011-2022 走看看