728x90
λ°μν
GCD(Greatest Common Divisor) μ΅λ 곡μ½μ ꡬνκΈ°
μ ν΄λ¦¬λ νΈμ λ² μ¬μ©
def gcd(a, b):
while b:
a, b = b, a % b
return a
a = b x q + r μ΄λΌκ³ νμ λ, GCD(a, b) = GCD(b, r)λ₯Ό λ§μ‘±νλ€.
κ°λ¨ μ¦λͺ :
μνμ μΌλ‘ μ¦λͺ νλ λ°©λ²μ΄ μμ§λ§ μ΄ν΄λ₯Ό μν΄μ κ°λ¨ν μ€λͺ νμλ©΄ μλμ κ°μ΄ ννν μ μλ€.
b = r x m + nμΌλ‘ ννν λ, nμ΄ 0μ΄λΌλ©΄ b = rmμΌλ‘ ννλλ€. μ¦, bμ rμ μ΅λ 곡μ½μ GCD(b, r) = mμ΄ λλ€.
a = bq + r = rmq + r = r(mq + 1) μ΄λ―λ‘ GCD(a, b) = r μ΄λ€.
=> GCD(a, b) = GCD(b, r) = GCD(r, 0) = r
LCM(Lowest Common Multiple) μ΅λ 곡μ½μ ꡬνκΈ°
def lcm(a, b):
return a // gcd(a, b) * b
aμ bμ μ΅λ 곡μ½μ GCD(a, b) = mμ΄λΌκ³ νμ λ,
a = Am, b = BmμΌλ‘ νν ν μ μλ€.
μ΄λ, μ΅λ 곡μ½μ(M) = ABm μ΄λ€.
λ°λΌμ a % m * b = Am % m * Bm = ABmμ΄ λλ€.
728x90
λ°μν