[JAVA] 백준 1929번 : 소수 구하기

조예빈·2024년 6월 30일
0

Coding Test

목록 보기
23/138
post-thumbnail

https://www.acmicpc.net/problem/1929
이 문제는 범위 내의 소수를 작은 수 부터 차례대로 출력하는 문제이다.

정답 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb = new StringBuffer();
        String[] input = br.readLine().split(" ");
        int M = Integer.parseInt(input[0]);
        int N = Integer.parseInt(input[1]);

        for (int i = M; i <= N; i++) {
            boolean isPrime = true;
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime && i > 1) {
                sb.append(i).append("\n");
            }
        }
        System.out.println(sb);
        br.close();
    }
}

profile
컴퓨터가 이해하는 코드는 바보도 작성할 수 있다. 사람이 이해하도록 작성하는 프로그래머가 진정한 실력자다. -마틴 파울러

0개의 댓글