Skip to main content

GCD && LCM

GCD

GCD(Great Common Divisor):

  • gcd(a,b)=d    n,mZ,an+bm=dgcd(a,b)=d \implies \exists n,m\in \Z, an + bm = d
  • let n,mZ,min(an+bm)=gcd(a,b)n,m \in \Z, \min(an+bm) = gcd(a,b)
  • We can also extent the definition to gcd a set of numbers

Co-prime:

  • gcd(a,b)=1    a,bgcd(a,b) = 1 \implies a,b are co-prime

LCM

LCM(Least Common Multiple):

  • lcm(a,b)=dlcm(a,b) = d means k1a=k2b=dk_1a = k_2b =d and dd is the smallest positive integer.

Some chinese content following about Euclid's algorithm

  • bZ,aZ,b=aq+k,q,kZ\forall b\in \Z, \exists a\in \Z, b = aq+k, q,k\in \Z

    • k=0    abk = 0\implies a|b
    • ac,bc,gcd(a,b)=1    abca|c,b|c, gcd(a,b) = 1\implies ab|c
    • abc,gcd(a,b)=1    aca|bc, gcd(a,b)= 1 \implies a|c
    • pab    papbp|ab \implies p|a \lor p|b
  • π(n)\pi(n) 表示n之前的质数数量, limnπ(n)/nlogn=1\lim_{n\to \infty }\pi(n)/n\log n = 1

  • PnP_n 表示第n个素数,其time complexity O(nlogn)O(n\log n)

  • i=1n1/i\sum_{i = 1}^n 1/i 的time complexity O(logn)O(\log n)1pn1/p\sum_{1\le p \le n} 1/pO(loglogn)O(\log \log n)

  • a,b,gcd(a,b)d    u,vZ,au+bv=d\forall a,b, gcd(a,b)|d \iff \exists u,v\in\Z, au + bv =d 裴蜀定理 (欧几里得算法扩展的基柱)

  • a,b,x,y,ax+by=d\forall a,b,x,y, ax + by = d 求解用欧几里得算法,先用gcd(a,b)gcd(a,b)x,yx,y并根据xx相应扩大

递归 gcdgcd 的写法基于欧几里得. gcd(a,b)=gcd(a,anb)=gcd(a,amod b)gcd(a,b) = gcd(a, a-nb) = gcd(a, a\mod \ b) (可以用induction 来证)

欧几里得算法e.g, 70x+81y=gcd(70,81)70x + 81y = gcd(70,81)

  1. 70(x+y)+11y=gcd(81,11)    70x+11y=gcd(81,11)70(x+y) + 11y = gcd(81,11)\implies 70x'+11y' = gcd(81,11)
  2. 11(6x+y)+4x=gcd(81,11)    11x+4y=111(6x'+y') + 4x' = gcd(81, 11) \implies 11x'' + 4y'' = 1 通过这里我们可以看到 x=y,y=xa/bxx' = y'', y' = x'' - a/b*x' 这里a/b=70/11a/b = 70/11
  3. 4(2x+y)+3x    4a+3b=14(2x'' + y'') + 3x'' \implies 4a+3b = 1
  4. 3(a+b)+a=1    3a+b=13(a+b) + a = 1 \implies 3a' + b' = 1
  5. 最小的解为 b=1,a=0b' = 1, a' =0
  6. a=b=1,a=a+b=0    b=1a = b' = 1, a' = a + b = 0 \implies b = -1
  7. b=x=1,a=2x+y=1    y=3b = x'' = -1, a = 2x'' + y'' = 1 \implies y'' = 3
  8. x=y=3,x=6x+y=1    y=19x' = y'' = 3, x'' = 6x' + y' = -1\implies y' = -19
  9. y=y=19,x=x+y=3    x=22y = y' = -19, x' = x + y = 3\implies x = 22
  10. x=22,y=19x = 22, y = -19 is the solution

将该算法抽象化, 我们得到 ax+by=gcd(a,b)ax + by = gcd(a,b)

  1. b(kx+y)+(a%b)x=gcd(a,b)b(kx + y) + (a\% b)x = gcd(a,b) where k=a/bk = a/b
  2. 将其再次抽象化 bx+(a%b)y=gcd(a,b)bx' + (a\%b)y' = gcd(a,b) 并重复1,2 直到3发生
  3. a%b==gcd(a,b)a \%b == gcd(a,b) 时我们可以得到最小解y=1,x=0y’= 1, x' = 0 在此时我们可以得到 x=y=1,y=xkxx = y' = 1, y = x' -kx 并通过该方式逐步往前推回从而得到式子的解

根据题目意思我们还可以将其写为其他方式,若要求 xy>0x,y > 0, 我们还可以总结出

  • 0<x+bk/d<b 0 < x + bk/d < b for some kZk\in \Z 如果k>0k > 0说明 x<0x < 0

lcm(a,b)=(a/gcd(a,b))blcm(a,b) = (a/gcd(a,b))*b