[TIL] 2024-12-13_GCD/LCM

YuriΒ·2024λ…„ 12μ›” 13일

TIL

λͺ©λ‘ 보기
7/59
post-thumbnail

πŸ“• Today I Learned - 였늘 λ‚΄κ°€ κ³΅λΆ€ν•œ 것을 μ •λ¦¬ν•©λ‹ˆλ‹€.

1. GCD(Greatest Common Divisor)

  • μ΅œλŒ€κ³΅μ•½μˆ˜λŠ” 두 수의 곡톡 μ•½μˆ˜ 쀑 μ΅œλŒ“κ°’μ„ λ§ν•œλ‹€.
    (μ•½μˆ˜λŠ” λ‚˜λˆ„μ–΄μ„œ 0이 λ˜λŠ” 수λ₯Ό λ§ν•œλ‹€.)
  • μ΄λ ‡κ²Œ λ‚˜λˆ„μ–΄μ„œ 0이 λ˜λŠ” 수 쀑 κ³΅ν†΅μ μœΌλ‘œ λ“€μ–΄κ°€ 있으며 κ·Έ 쀑 μ΅œλŒ€κ°’μ΄ μ΅œλŒ€κ³΅μ•½μˆ˜μ΄λ‹€.
  • μžλ°”μ—μ„œλŠ” BigInteger ν΄λž˜μŠ€μ— μ΅œλŒ€ κ³΅μ•½μˆ˜λ₯Ό ꡬ할 수 μžˆλŠ” gcd() ν•¨μˆ˜λ₯Ό μ œκ³΅ν•œλ‹€.

1) BigInteger 클래슀

import java.math.BigInteger;

public class Gcd {
    public static void main(String[] args) {
        System.out.println(gcd(48, 32));
    }

    private static int gcd(int a, int b) {
        BigInteger bigA = BigInteger.valueOf(a);
        BigInteger bigB = BigInteger.valueOf(b);
        BigInteger gcd = bigA.gcd(bigB);
        return gcd.intValue();
    }
}

2) 직접 κ΅¬ν˜„: μœ ν΄λ¦¬λ“œ ν˜Έμ œλ²•

1. 큰 수(num1) μ—μ„œ μž‘μ€ 수(num2)λ₯Ό λ‚˜λˆˆλ‹€.
2. λ‚˜λ¨Έμ§€(num1 % num2)κ°€ 0이 μ•„λ‹ˆλΌλ©΄ λ‚˜λ¨Έμ§€μ™€ μž‘μ€ 수(num2)둜 1λ²ˆλΆ€ν„° λ‹€μ‹œ μ‹œμž‘
3. [μž¬κ·€ν˜ΈμΆœ] 1~2의 과정을 λ°˜λ³΅ν•΄μ„œ λ‚˜λ¨Έμ§€κ°€ 0 이라면 κ·Έ μˆ˜κ°€ μ΅œλŒ€κ³΅μ•½μˆ˜

public static int getGcd(int p, int q) {
        if (q == 0) return p;
        else return getGcd(q, p % q);
}

2. LCM(Least Common Multiple)

μ΅œμ†Œκ³΅λ°°μˆ˜λž€ 두 μˆ˜μ—μ„œ μ„œλ‘œ κ³΅ν†΅μœΌλ‘œ μ‘΄μž¬ν•˜λŠ” 배수 쀑 κ°€μž₯ μž‘μ€ 수λ₯Ό 가리킨닀.
μ΅œμ†Œκ³΅λ°°μˆ˜μ˜ 경우 두 수λ₯Ό κ³±ν•˜κ³  κ·Έ 값에 μ΅œλŒ€κ³΅μ•½μˆ˜λ₯Ό λ‚˜λˆˆ κ°’μœΌλ‘œ ꡬ할 수 μžˆλ‹€.

1) BigInteger 클래슀

import java.math.BigInteger;

public class Lcm {
    public static void main(String[] args) {
        System.out.println(lcm(48, 32));
    }

    public static int lcm(int a, int b) {
        BigInteger bigA = BigInteger.valueOf(a);
        BigInteger bigB = BigInteger.valueOf(b);
        BigInteger lcm = (bigA.multiply(bigB)).divide(bigA.gcd(bigB));
        return lcm.intValue();
    }
}

2) 직접 κ΅¬ν˜„: μ΅œλŒ€κ³΅μ•½μˆ˜ μ‚¬μš©

public static int getGcd(int p, int q) {
    if (q == 0) return p;
    else return getGcd(q, p % q);
}
    
public static int getLcm(int p, int q) {
    return (p * q) / getGcd(p, q);
}

πŸ’­ μ•Œκ³ λ¦¬μ¦˜ λ¬Έμ œμ—μ„œ μ΅œλŒ€κ³΅μ•½μˆ˜μ™€ μ΅œμ†Œκ³΅λ°°μˆ˜ κ°œλ…μ΄ λ‚˜μ™€ λ‹€μ‹œ ν•œλ²ˆ 정리해 λ³΄μ•˜λ‹€. 곡뢀 ν•΄μ•Όν• κ²Œ λ„ˆλ¬΄ λ§Žμ§€λ§Œ μ‘°κΈ‰ν•΄ν•˜μ§€ 말고 μ„±μ‹€ν•˜κ²Œ 즐겨보자 😎

profile
μ•ˆλ…•ν•˜μ„Έμš” :)

0개의 λŒ“κΈ€