定理: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);
}