π Today I Learned - μ€λ λ΄κ° 곡λΆν κ²μ μ 리ν©λλ€.
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();
}
}
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);
}
μ΅μ곡배μλ λ μμμ μλ‘ κ³΅ν΅μΌλ‘ μ‘΄μ¬νλ λ°°μ μ€ κ°μ₯ μμ μλ₯Ό κ°λ¦¬ν¨λ€.
μ΅μ곡배μμ κ²½μ° λ μλ₯Ό κ³±νκ³ κ·Έ κ°μ μ΅λ곡μ½μλ₯Ό λλ κ°μΌλ‘ ꡬν μ μλ€.
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();
}
}
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);
}
π μκ³ λ¦¬μ¦ λ¬Έμ μμ μ΅λ곡μ½μμ μ΅μ곡배μ κ°λ μ΄ λμ λ€μ νλ² μ λ¦¬ν΄ λ³΄μλ€. κ³΅λΆ ν΄μΌν κ² λ무 λ§μ§λ§ μ‘°κΈν΄νμ§ λ§κ³ μ±μ€νκ² μ¦κ²¨λ³΄μ π