본문 바로가기
Problem Solving/Baekjoon

[백준] 14914 사과와 바나나 나눠주기 - Brute Force / Java

by graycode 2024. 2. 27.

 문제 링크

 

14914번: 사과와 바나나 나눠주기

아름이가 나누어 줄 수 있는 경우를 모두 출력해야 하며, 각 경우마다 친구의 수, 사과 개수, 바나나 개수 차례로 한 줄에 각각 빈칸으로 구분하여 출력한다. 각 경우마다 중복없이 한 번만 출력

www.acmicpc.net

 

 풀이 코드

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();

        int a = read(), b = read(), min = Math.min(a, b);
        for (int i = 1; i <= min; i++)
            if (a % i == 0 && b % i == 0) sb.append(i).append(" ").append(a / i).append(" ").append(b / i).append("\n");

        bw.write(sb.toString());
        bw.flush();
    }

    private static int read() throws IOException {
        int c, n = System.in.read() & 15;
        while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);

        return n;
    }

}

댓글