Algorithm-math.md


  • μ§„μˆ˜, 진법

  • μ΅œμ†Œκ³΅λ°°μˆ˜, μ΅œλŒ€κ³΅μ•½μˆ˜

μ§„μˆ˜μ™€ 진법


  • N μ§„λ²•μœΌλ‘œ λ¬Έμžμ—΄μ„ λ³€ν™˜ν•˜κΈ°

def stoi(s, n):
    ret = 0
    l = len(s)
    for i in range(l): ret += int(s[i]) * n**(l-i-1)
    return ret

=> ν™œμš©

  • κ±°λ“­μ œκ³± μ—°μ‚° baekjoon1629번

  • 쑰건문 + Nμ§„μˆ˜ λ³€ν™˜ λ°©λ²•μœΌλ‘œ ν•΄κ²° κ°€λŠ₯ doublemulimage

def pow_custom(a, b):
    ret = 1
    while b:
        if b % 2 == 1: ret *= a
        a = a*a
        b //= 2
    return ret
  • 큰 수λ₯Ό κ³±ν•˜λŠ” 것은 Pythonμ—μ„œλ„ 느리기 λ•Œλ¬Έμ— λͺ¨λ“ˆλŸ¬ μ—°μ‚°μžλ₯Ό 쀑간쀑간에 μ“°μž!

μ΅œλŒ€κ³΅μ•½μˆ˜μ™€ μ΅œμ†Œκ³΅λ°°μˆ˜


  • μ΅œλŒ€κ³΅μ•½μˆ˜(GCD) : κ³΅μ•½μˆ˜ 쀑 μ΅œλŒ“κ°’

    • μ΅œλŒ€κ³΅μ•½μˆ˜κ°€ 1이면 μ„œλ‘œμ†Œ

  • μ΅œμ†Œκ³΅λ°°μˆ˜(LCM) : 곡배수 쀑 μ΅œμ†Œκ°’

LCM(A, B) = A * B / GCD(A, B)

=> GCD만 잘 κ΅¬ν•˜λ©΄ LCM은 O(1)에 ꡬ할 수 μžˆλ‹€.

  • μ΅œλŒ€κ³΅μ•½μˆ˜

# μ •λ°©ν–₯ 체크
def gcd(a, b):
    ret = 0
    for i in range(min(a, b)):
        if a % i == 0 and b % i == 0:
            ret = i
    return ret

# μ—­λ°©ν–₯ 체크 => 더 빠름
def gcd(a, b):
    for i in range(min(a, b), 0, -1):
        if a % i == 0 and b % i == 0:
            return i
  • βœ… πŸ˜€μœ ν΄λ¦¬λ“œ ν˜Έμ œλ²•

    • μœ„μ˜ 두 방식보닀 훨씬 λΉ λ₯΄λ‹€

GCD(A, B) = GCD(B, A % B)

# 속도 => O(log N)
def gcd(a, b):
    return b if a % b == 0 else gcd(b, a%b)

μ†Œμˆ˜μ™€ μ†ŒμΈμˆ˜λΆ„ν•΄


  • μ—¬λŸ¬κ°€μ§€ μ†Œμˆ˜ νŒλ³„λ²•

# 2λΆ€ν„° N-1κΉŒμ§€ 체크
def isPrime(N):
    for i in range(2, N):
        if N % i == 0: return False
    return True
# 2λΆ€ν„° sqrt(N)κΉŒμ§€ 체크 
def isPrime(N):
    i = 2
    while i*i <= N:
        if N % i == 0: return False
    return True

μ—λΌν† μŠ€ν…Œλ„€μŠ€μ˜ 체

eratostenes

def era(N):
    ck, p = [False for _ in range(N+1)], []
    for i in range(2, N+1):
        if ck[i] == True: continue
        p.append(i)
        for j in range(i*i, N+1, i):
            ck[j] = True
    return ck, p

Last updated