코딩테스트

[백준 / 실버4] 3036 : 링 (JAVA)

lyndaa 2023. 3. 27. 17:33

문제


풀이 방법

  • 반복문을 통해 첫번째 링과 다른 링들을 순서대로 비교하여 몇바퀴 도는지 알아낸다.
  • 최대공약수를 구한 후 각각의 둘레값에 나눠서 기약 분수 형태로 출력한다.

코드

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 IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int gcd;
        int n = Integer.parseInt(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());

        int first= Integer.parseInt(st.nextToken());
        while(st.hasMoreTokens()){
            int other = Integer.parseInt(st.nextToken());
            gcd = gcd(first,other);
            sb.append(first/gcd).append("/").append(other/gcd).append("\n");
        }

        System.out.print(sb);

    }
    public static int gcd(int a, int b){
        int n = 0;
        while(b!=0){
            n = a%b;
            a = b;
            b = n;
        }
        return a;
    }
}