File tree Expand file tree Collapse file tree 1 file changed +26
-4
lines changed
Expand file tree Collapse file tree 1 file changed +26
-4
lines changed Original file line number Diff line number Diff line change 11package leetcodeEasyLevel ;
22
33public class _0204countPrimes {
4+
45 //prime numbers 즉 소수를 찾는 문제
56 public static int countPrimes (int n ) {
6- for (int i =0 ; i <n ; i ++){
7- System .out .println (" " +n );
7+ boolean [] nums = new boolean [n ];
8+ int primeCount = 0 ;
9+ // 1부터 n까지의 숫자를 true로 초기화한다.
10+ for (int i = 0 ; i < n ; i ++) {
11+ nums [i ] = true ;
12+ }
13+
14+ //제곱이 가능한 숫자는 false로 변경한다.
15+ for (int i = 2 ; i * i < n ; i ++) {
16+ //false를 true 바꾸지 않도록 조건을 건다.
17+ if (nums [i ] == true ) {
18+ //배수들은 다 false로 변경한다.
19+ for (int j = 2 ; j * i < n ; j ++) {
20+ nums [j * i ] = false ;
21+ }
22+ }
23+ }
24+
25+ //true만 세기
26+ for (int i = 2 ; i < n ; i ++) {
27+ if (nums [i ] == true ) {
28+ primeCount ++;
29+ }
830 }
9- return 0 ;
31+ return primeCount ;
1032 }
1133
1234 public static void main (String [] args ) {
13- int n = 10 ; //=> 4
35+ int n = 10 ; //=> 4
1436 System .out .println (countPrimes (n ));
1537 }
1638}
You can’t perform that action at this time.
0 commit comments