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