算法-歐幾里得算法(輾轉相除法)

定理:gcd(a,b) = gcd(b,a mod b) (a>b 且a mod b 不爲0)

gcd:greatest common divisor--最大公約數

mod:取餘

a,b的最大公約數等於b與a對b取得餘數的最大公約數。

c語言:

/*歐幾里德算法:輾轉求餘
原理: gcd(a,b)=gcd(b,a mod b)
當b爲0時,兩數的最大公約數即爲a
getchar()會接受前一個scanf的回車符
*/
#include<stdio.h>
unsigned int Gcd(unsigned int M,unsigned int N)
{
     unsigned int Rem;
     while(N > 0)
    {
       Rem = M % N;
       M = N;
       N = Rem;
    }
    return M;
}
int main(void)
{
    int a,b;
    scanf("%d %d",&a,&b);
    printf("the greatest common factor of %d and %d is ",a,b);
    printf("%d\n",Gcd(a,b));
    return 0;
}

c++:

#include <algorithm> // std::swap for c++ before c++11
#include <utility> // std::swap for c++ since c++11
int gcd(int a,int b)
{
    if (a < b)
        std::swap(a, b);
    return b == 0 ? a : gcd(b, a % b);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章