본문 바로가기
알고리즘 공부/백준

[JAVA 백준 25일차 / 하루 3문제] 2581번, 11653번, 27323번

by maverick11471 2025. 2. 27.

1. 2581번 소수

import java.io.*;

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

        int M = Integer.parseInt(br.readLine());
        int N = Integer.parseInt(br.readLine());

        int sum = 0;
        int min = Integer.MAX_VALUE;

        for (int i = M; i <= N; i++) {
            if (isPrime(i)) {
                sum += i;
                if (min == Integer.MAX_VALUE) {
                    min = i;
                }
            }
        }

        if (sum == 0) {
            System.out.println(-1);
        } else {
            System.out.println(sum);
            System.out.println(min);
        }
    }

    private static boolean isPrime(int num) {
        if (num < 2) return false;
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) return false;
        }
        return true;
    }
}
  • 1 × 36
    2 × 18
    3 × 12
    4 × 9
    6 × 6 (여기서 대칭이 시작됨)
    9 × 4
    12 × 3
    18 × 2
    36 × 1
    여기서 6×6을 기준으로 대칭을 이루기 때문에, 6까지만 확인하면 나머지 약수도 자동으로 확인된 것과 같음.

2. 11653번 소인수 분해

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());

        for (int i = 2; i * i <= N; i++) { // 2부터 √N까지 나눠봄
            while (N % i == 0) { // i로 나눠지면 계속 나누고 출력
                System.out.println(i);
                N /= i;
            }
        }

        if (N > 1) { // 마지막으로 남은 값이 1보다 크다면 그것도 소수
            System.out.println(N);
        }
    }
}

3. 27323번 직사각형

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input = br.readLine().split(" ");
        int A = Integer.parseInt(input[0]);
        int B = Integer.parseInt(input[1]);
        
        System.out.println(A * B); // 넓이 출력
    }
}