본문 바로가기

IT/알고리즘

백준 9단계(4948)

반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 
public class Main {
    
    //1
    //10
    //13
    //100
    //1000
    //10000
    //100000
    //0
    
    //result
    
    //1
    //4
    //3
    //21
    //135
    //1033
    //8392
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    
        //n이 0이 입력될때까지 반복 처리
        int n;
        while((n = Integer.parseInt(br.readLine())) != 0){
            
            //sieve of eratosthenes
            boolean[] bool = new boolean[2 * n + 1];
            for(int i = 1; i < bool.length; i++) {
                bool[i] = true;
            }
            
            for(int i = 2; i < Math.sqrt(bool.length) ; i++) {
                if(bool[i]) {
                    for(int j = i * i; j < bool.length; j += i) {
                        bool[j] = false;
                    }
                }
            }
            //시작 번호 + 1을해서 처리를 해야한다, 그 이유는 13을 입력했을때 
            //시작 번호를 포함하면 4개 소수이지만 포함을 안하면 3개 소수를 출력한다
            int cnt = 0;
            for(int i = n + 1; i <= 2*n; i++) {
                if(bool[i]) cnt++;
            }
            bw.write(String.valueOf(cnt) + "\n");
            
        }
        bw.flush();
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 
반응형

'IT > 알고리즘' 카테고리의 다른 글

백준 9단계(9020)  (0) 2019.12.22
백준 9단계(1929)  (0) 2019.12.22
백준 9단계(2581)  (0) 2019.12.22
백준 9단계(1978)  (0) 2019.12.21
백준 8단계(1011)  (0) 2019.12.21