Post

[BaekJoon] #5086 - 배수와 약수 [Java][C++][Python]

[BaekJoon] #5086 - 배수와 약수 [Java][C++][Python]

문제 링크


1. 아이디어

두 수가 약수와 배수 중 어떤 관계인지 판정하는 문제로, 첫 번째 숫자를 $a$, 두 번째 숫자를 $b$라 하면 $a$가 $b$의 배수일 때 $a$를 $b$로 나눈 나머지가 0이고, $a$가 $b$의 약수일 때 $b$를 $a$로 나눈 나머지가 0이다. $a$가 $b$의 약수이면서 배수이면 두 수가 같아야 하는데 같은 경우는 없으므로 두 조건은 동시에 성립하지 않아 차례로 검사하면 된다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        while (true) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());

            if (a == 0) break;

            if (a % b == 0) {
                bw.write("multiple\n");
            } else if (b % a == 0) {
                bw.write("factor\n");
            } else {
                bw.write("neither\n");
            }
        }

        bw.flush();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    while (true) {
        int a, b;
        cin >> a >> b;

        if (a == 0) break;

        if (a % b == 0) {
            cout << "multiple\n";
        } else if (b % a == 0) {
            cout << "factor\n";
        } else {
            cout << "neither\n";
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import sys

input = sys.stdin.readline

while True:
    a, b = map(int, input().split())
    if a == 0:
        break

    if a % b == 0:
        print("multiple")
    elif b % a == 0:
        print("factor")
    else:
        print("neither")

This post is licensed under CC BY 4.0 by the author.