Skip to content

Commit d3fcf11

Browse files
authored
Create 2.java
1 parent ea19bc3 commit d3fcf11

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

20/2.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import java.util.*;
2+
3+
class Main {
4+
public static int n = 1000; // 2부터 1,000까지의 모든 수에 대하여 소수 판별
5+
public static boolean[] arr = new boolean[n + 1];
6+
7+
public static void main(String[] args) {
8+
Arrays.fill(arr, true); // 처음엔 모든 수가 소수(True)인 것으로 초기화(0과 1은 제외)
9+
// 에라토스테네스의 체 알고리즘 수행
10+
// 2부터 n의 제곱근까지의 모든 수를 확인하며
11+
for (int i = 2; i <= Math.sqrt(n); i++) {
12+
// i가 소수인 경우(남은 수인 경우)
13+
if (arr[i] == true) {
14+
// i를 제외한 i의 모든 배수를 지우기
15+
int j = 2;
16+
while (i * j <= n) {
17+
arr[i * j] = false;
18+
j += 1;
19+
}
20+
}
21+
}
22+
// 모든 소수 출력
23+
for (int i = 2; i <= n; i++) {
24+
if (arr[i]) System.out.print(i + " ");
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)