最大公约数(GCD)

Published on7/29/2025
Created on 10/18/2021

GCD abbr. of Greatest Common Divisor(最大公约数) 另一个名称是 Highest Common Factor

链接

定义

gcd(a,b)=max{d  a=de  b=df,d,e,fZ}(a,bZ)\gcd(a,b)=max\{d\ |\ a=de\ \wedge\ b=df,\quad d,e,f\in\mathbb{Z}\}\quad(a,b\in\mathbb{Z})

性质

辗转相除法

C/C++ 非递归版本

int gcd(int m, int n) {
 int t = 1;
 while (t != 0) {
  t = m % n;
  m = n;
  n = t;
 }
 return m;
}

C/C++ 递归版本

template<typename T>
T gcd(T a,T b){
 return b?gcd(b,a%b):a;
}

时间复杂度:O(logn)\mathrm{O}(\log n) 参考