Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8f6bd17

Browse files
committed
고다혜: [BOJ] 1644 소수의 연속합_250327
1 parent f653ef2 commit 8f6bd17

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

‎BOJ/1000-5000번/DH_1644.java

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import java.io.*;
2+
3+
/*
4+
* 소수의 연속합
5+
*/
6+
7+
public class DH_1644 {
8+
public static void main(String[] args) throws Exception {
9+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10+
11+
int N = Integer.parseInt(br.readLine());
12+
13+
// N까지 숫자 중에서 어떤 것이 소수인지 알아내기
14+
boolean[] isNotPrime = getNotPrime(N);
15+
16+
System.out.println(getCount(isNotPrime, N));
17+
}
18+
19+
// 투포인터를 통해 소수의 연속합을 구했을 때, n이 되는 개수 구하기
20+
static int getCount(boolean[] isNotPrime, int n) {
21+
int count = 0;
22+
23+
int s = 2, e = 2, sum = 2;
24+
25+
while(s <= e && e < isNotPrime.length) {
26+
// e 옮기기
27+
if(sum < n) {
28+
29+
while(e < isNotPrime.length) {
30+
31+
e += 1;
32+
33+
if(isNotPrime.length == e) break;
34+
35+
if(!isNotPrime[e]) {
36+
sum += e;
37+
break;
38+
}
39+
}
40+
}
41+
42+
// sum >= n → s 옮기기
43+
else {
44+
if(sum == n) count += 1;
45+
46+
sum -= s;
47+
48+
while(s < e) {
49+
s += 1;
50+
51+
if(!isNotPrime[s]) {
52+
break;
53+
}
54+
}
55+
}
56+
}
57+
58+
return count;
59+
}
60+
61+
// 에라토스테네스 체로 n까지 숫자 중에서 소수 걸러내기
62+
static boolean[] getNotPrime(int n) {
63+
boolean[] isNotPrime = new boolean[n + 1];
64+
65+
isNotPrime[0] = true;
66+
isNotPrime[1] = true;
67+
68+
for(int i = 2; i <= Math.sqrt(isNotPrime.length); i++) {
69+
if(isNotPrime[i]) continue;
70+
71+
for(int j = i * i; j < isNotPrime.length; j += i) {
72+
isNotPrime[j] = true;
73+
}
74+
}
75+
76+
return isNotPrime;
77+
}
78+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /