
앞의 유클리드 호제법을 우려먹는 문제. 모르시는 분은 다음을 참조하자.
https://mewtwo.tistory.com/192
2609. 최대공약수와 최소공배수 (자바, Java)
이 문제를 통해 유클리드 호제법을 배웠다. 유클리드 호제법이란, a>b인 두 수 a와 b의 최대공약수는 a를 b로 나눈 나머지인 r과 b의 최대공약수이기도 한다는 것이다. 증명은 다음을 참고. https://ko
mewtwo.tistory.com
같은 원리로 풀어주면 된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i=0; i<n; i++) {
String str = br.readLine();
StringTokenizer st = new StringTokenizer(str, " ");
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
System.out.println(lcm(x,y));
}
}
static int gcd(int x, int y) {
if (x>y) {
int temp = x;
x = y;
y = temp;
}
if (x==0) return y;
return gcd(y%x, x);
}
static int lcm(int x, int y) {
return (x * y) / gcd(x,y);
}
}'백준 문제풀이' 카테고리의 다른 글
| 11050. 이항계수 (자바, Java) (0) | 2022.10.24 |
|---|---|
| 3036. 링 (자바, Java) (0) | 2022.10.24 |
| 2609. 최대공약수와 최소공배수 (자바, Java) (0) | 2022.10.24 |
| 1037. 약수 (자바, Java) (0) | 2022.10.24 |
| 5086. 배수와 약수 (자바, Java) (0) | 2022.10.24 |