728x90
2609번: 최대공약수와 최소공배수
첫째 줄에는 입력으로 주어진 두 수의 최대공약수를, 둘째 줄에는 입력으로 주어진 두 수의 최소 공배수를 출력한다.
www.acmicpc.net
문제
두 개의 자연수를 입력받아 최대 공약수와 최소 공배수를 출력하는 프로그램을 작성하시오.
입력
첫째 줄에는 두 개의 자연수가 주어진다. 이 둘은 10,000이하의 자연수이며 사이에 한 칸의 공백이 주어진다.
출력
첫째 줄에는 입력으로 주어진 두 수의 최대공약수를, 둘째 줄에는 입력으로 주어진 두 수의 최소 공배수를 출력한다.
코드
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int[] a = new int [2]; int[][] b = new int [2][10000]; int temp=2; for(int i=0;i<2;i++) { a[i] = Integer.parseInt(st.nextToken()); temp=2; while(a[i]>1 && temp<=a[i]) { if(a[i]%temp==0) { b[i][temp]++; a[i]/=temp; } else temp++; } } int gcd=1, lcm=1; for(int i=0;i<10000;i++) if(Math.min(b[0][i], b[1][i])!=0) gcd*=Math.pow(i, Math.min(b[0][i], b[1][i])); for(int i=0;i<10000;i++) if(Math.max(b[0][i], b[1][i])!=0) lcm*=Math.pow(i,Math.max(b[0][i], b[1][i])); System.out.println(gcd); System.out.println(lcm); } }
728x90
728x90
'Algorithm > Baekjoon' 카테고리의 다른 글
Baekjoon 1929 소수 구하기 JAVA (0) | 2022.01.14 |
---|---|
Baekjoon 10828 스택 JAVA (0) | 2022.01.14 |
Baekjoon 2751 수 정렬하기 2 JAVA (0) | 2022.01.14 |
Baekjoon 2750 수 정렬하기 JAVA (0) | 2022.01.14 |
Baekjoon 10845 큐 JAVA (0) | 2022.01.14 |
댓글