๊ธฐ๋ก๋ฐฉ

BOJ_2581 : ์†Œ์ˆ˜ ๋ณธ๋ฌธ

CodingTest/Java

BOJ_2581 : ์†Œ์ˆ˜

Soom_1n 2022. 9. 29. 12:13

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

2581๋ฒˆ: ์†Œ์ˆ˜

M์ด์ƒ N์ดํ•˜์˜ ์ž์—ฐ์ˆ˜ ์ค‘ ์†Œ์ˆ˜์ธ ๊ฒƒ์„ ๋ชจ๋‘ ์ฐพ์•„ ์ฒซ์งธ ์ค„์— ๊ทธ ํ•ฉ์„, ๋‘˜์งธ ์ค„์— ๊ทธ ์ค‘ ์ตœ์†Ÿ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.  ๋‹จ, M์ด์ƒ N์ดํ•˜์˜ ์ž์—ฐ์ˆ˜ ์ค‘ ์†Œ์ˆ˜๊ฐ€ ์—†์„ ๊ฒฝ์šฐ๋Š” ์ฒซ์งธ ์ค„์— -1์„ ์ถœ๋ ฅํ•œ๋‹ค.

www.acmicpc.net



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • m๊ณผ n ์‚ฌ์ด์˜ ์†Œ์ˆ˜๋“ค์˜ ํ•ฉ๊ณผ ์ตœ์†Œ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

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));
        int m = Integer.parseInt(br.readLine());
        int n = Integer.parseInt(br.readLine());

        boolean prime[] = new boolean[n+1];
        prime[1] = true;
        for (int i = 2; i <= n; i++) {
            int c = 1;
            if (!prime[i*c++]) {
                while (i*c <= n) {
                    prime[i*c++] = true;
                }
            }
        }

        long sum = 0;
        int min = 0;
        for (int i = m; i <= n; i++){
            if (!prime[i]) {
                sum += i;
                if (min == 0) min = i;
            }
        }
        if (min == 0) System.out.println(-1);
        else System.out.println(sum + "\n" + min);
    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • m๊ณผ n์„ ์ž…๋ ฅ๋ฐ›๊ณ , n๊นŒ์ง€์˜ ์†Œ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
    • boolean ๋ฐฐ์—ด prime์„ ์„ ์–ธํ•ด i๋ฅผ 2๋ถ€ํ„ฐ n๊นŒ์ง€ ์ฆ๊ฐ€์‹œํ‚ค๋ฉฐ ๊ณ„์‚ฐํ•œ๋‹ค.
    • i์˜ ๊ณฑ์€ i๊ฐ€ ์•ฝ์ˆ˜๊ฐ€ ๋˜๋ฏ€๋กœ ์†Œ์ˆ˜๊ฐ€ ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐฐ์—ด prime์— true๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.
    • prime[0]์€ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , prime[1]์€ 1์ด ์•ฝ์ˆ˜๊ฐ€ ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋”ฐ๋กœ true๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.
  • ๋ฐฐ์—ด prime์˜ m~n ๋ฒ”์œ„๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ ํ•ฉ๊ณผ ์ตœ์†Œ๊ฐ’์„ ๊ณ„์‚ฐํ•ด ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ์˜ค๋žœ๋งŒ์— ์†Œ์ˆ˜ ๊ด€๋ จ ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ดค๋Š”๋ฐ, ์กฐ๊ธˆ ์ฝ”๋“œ ์ˆ˜์ •์„ ํ•ด๊ฐ€๋ฉฐ ์†Œ์ˆ˜ ๊ณ„์‚ฐ์„ ํ–ˆ์ง€๋งŒ ์›๋ฆฌ๋ฅผ ์•Œ๊ณ  ์žˆ์œผ๋‹ˆ ๊ธˆ๋ฐฉ ๋‹ต์„ ์ฐพ์„ ์ˆ˜ ์žˆ์—ˆ๋‹ค.
  • ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค๊ฐ€ ๋‚˜์™€์„œ ๋ฐ˜๋ก€๋ฅผ ์ฐพ๊ธฐ์œ„ํ•ด 0/0 , 1/10,000 ์„ ๋„ฃ์–ด๋ณด๋‹ค๊ฐ€ prime[1]์ด true๊ฐ€ ์•ˆ๋˜์–ด ์žˆ์–ด์„œ ์˜ค๋ฅ˜๊ฐ€ ๋‚˜๋Š”๊ฑธ ์ฐพ์•„๋ƒˆ๋‹ค.

728x90

'CodingTest > Java' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ_10815 : ์ˆซ์ž ์นด๋“œ  (0) 2022.10.01
BOJ_1427 : ์†ŒํŠธ์ธ์‚ฌ์ด๋“œ  (0) 2022.09.30
BOJ_4673 : ์…€ํ”„ ๋„˜๋ฒ„  (0) 2022.09.28
BOJ_1253 : ์ข‹๋‹ค  (0) 2022.09.24
BOJ_1940 : ์ฃผ๋ชฝ  (0) 2022.09.24