728x90
문제
주어진 숫자들 중 소수가 몇 개인지 찾아서 출력하는 프로그램을 작성하시오.
입력
첫 줄에 수의 개수 N이 주어진다. N은 100이하이다. 다음으로 N개의 줄에 걸쳐 N개의 수가 주어지는데 수는 1,000 이하의 자연수이다.
출력
주어진 수들 중 소수의 개수를 출력한다.
예제 입력
4
1 3 5 7
예제 출력
3
// 코드
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
|
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception {
// Please Enter Your Code Here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n > 0) {
int[] myArr = new int[n];
int maxVal = -987987987;
for(int i = 0; i < n; i++) {
myArr[i] = sc.nextInt();
if(myArr[i] > maxVal) {
maxVal = myArr[i];
}
}
List<Integer> primeList = new ArrayList<>();
int[] arr = new int[maxVal+1];
arr[0] = 1;
arr[1] = 1;
for(int i = 2; i <= maxVal; i++) {
if(arr[i] == 0) {
primeList.add(i);
for(int j = i; j <= maxVal;) {
arr[j] = 1;
j += i;
}
}
}
int totCnt = 0;
for(int num : primeList) {
for(int i = 0; i < myArr.length; i++) {
if(num == myArr[i]) {
totCnt += 1;
}
}
}
System.out.println(totCnt);
} else {
System.out.println(0);
}
}
}
|
cs |
반응형