Skip to content

Commit ac4cae4

Browse files
committed
Add code to find prime number
1 parent 90011b3 commit ac4cae4

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package algorithm.basic;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.CoreMatchers.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
public class FindPrimeNumTest {
9+
10+
/*
11+
TASK
12+
주어지는 수 이하의 소수 개수를 구한다.
13+
*/
14+
15+
@Test
16+
public void test() {
17+
assertThat(solution(-3), is(-1));
18+
assertThat(solution(0), is(0));
19+
assertThat(solution(1), is(0));
20+
assertThat(solution(2), is(1));
21+
assertThat(solution(3), is(2));
22+
assertThat(solution(8), is(4));
23+
assertThat(solution(12), is(5));
24+
assertThat(solution(44), is(14));
25+
//2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43
26+
}
27+
28+
public int solution(int num) {
29+
if (num < 0) {
30+
return -1;
31+
}
32+
int[] checkList = new int[num + 1];
33+
34+
for (int i = 2; i <= num; i++) {
35+
checkList[i] = i;
36+
}
37+
int baseNum = (int) Math.sqrt(num);
38+
39+
for (int i = 2; i <= baseNum; i++) {
40+
if (checkList[i] == 0) {
41+
continue;
42+
}
43+
for (int k = i; k <= num; k += i) {
44+
if (checkList[k] != i && checkList[k] % i == 0) {
45+
checkList[k] = 0;
46+
}
47+
}
48+
}
49+
50+
int count = 0;
51+
for (int i = 0; i <= num; i++) {
52+
if (checkList[i] != 0) {
53+
count++;
54+
}
55+
}
56+
57+
return count;
58+
}
59+
}

0 commit comments

Comments
 (0)