본문 바로가기
Algorithm/Baekjoon Online Judge

[Java] [Math] 백준 1929 소수 구하기 실버3

by 제우제우 2024. 5. 4.

https://www.acmicpc.net/problem/1929

import java.util.*;
import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int start = Integer.parseInt(st.nextToken());
        int end   = Integer.parseInt(st.nextToken()); // (1 ≤ M ≤ N ≤ 1,000,000)

        boolean [] memo = new boolean[end+1];
        memo[0] = true;
        memo[1] = true;
        StringBuilder sb = new StringBuilder();
        for (int i = 2; i <= end; i++) {
            if(memo[i]) continue;
            if(i >= start) sb.append(i).append("\n");
            for (long j = 2; j * i <= end; j++) {
                memo[(int)j * i] = true;
            }
        }
        System.out.println(sb);
    }
}