Contents

[백준 2581]소수 - JAVA 풀이

   Aug 24, 2021     1 min read     - Comments

바로가기

문제

문제


해석

  1. M과 N이 주어졌을 때, M과 N사이의 소수의 합가장 작은 소수를 출력하는 문제

풀이

  • 소수를 구하는 방법은 1978문제와 동일하다. 바로가기

코드

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));
        
        int M = Integer.parseInt(br.readLine());
        int N = Integer.parseInt(br.readLine());         
        boolean[] c = calc();
        
        int min = 0, sum = 0;
        
        for(int i = M; i <= N; i++){
            if(!c[i]){
                if(min == 0)
                    min = i;
                sum += i;
            }                
        }
        if(min == 0)
            System.out.println("-1");
        else
            System.out.println(sum + "\n" + min);
    }
    
    public static boolean[] calc(){
        boolean[] check = new boolean[10001];
        check[1] = true;
        
        for(int i = 2; i < 10001; i++){
            if(check[i])
                continue;
            for(int j = i*2; j < 10001; j+=i)
                check[j] = true;            
        }
        
        return check;
    }
}