최대공약수(GCD)
GCD는 Greatest Common Divisor의 약자로 최대공약수이다.
두 수의 약수들의 공통된 값 중 최댓값을 말한다.
GCD를 구하는 방법을 알아보자.
1. BigInteger 내장 함수
private static int gcd(int a, int b) {
BigInteger n = BigInteger.valueOf(a);
BigInteger m = BigInteger.valueOf(b);
return n.gcd(m).intValue();
}
2. 재귀
private static int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
3. 반복문
private static int gcd(int a, int b) {
int n = a;
int m = b;
if (a < b) {
n = a;
m = b;
}
int tmp;
while (m != 0) {
tmp = n % m;
n = m;
m = tmp;
}
return n;
}
최소공배수(LCM)
최소공배수는 구한 GCD를 이용해 구할 수 있다.
두 수 a와 b를 곱하고 최대공약수로 나눠주면 최소공배수가 된다.
private static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
'TIL' 카테고리의 다른 글
[스프링] [JPA] 페이징 성능 개선: 커버링 인덱스 (0) | 2024.05.19 |
---|---|
[트러블슈팅] 젠킨스 디스크 용량 부족 (0) | 2024.05.19 |
[트러블슈팅] ConcurrentModificationException (0) | 2024.05.18 |
[자료구조] 스택 & 큐 (0) | 2024.05.18 |
[알고리즘] 이분 탐색 - JAVA (0) | 2024.05.17 |
[네트워크] 컴퓨터네트워크 및 인터넷 역사 (0) | 2024.05.17 |