주어진 수 N개 중에서 소수가 몇 개인지 찾아서 출력하는 프로그램을 작성하시오.
첫 줄에 수의 개수 N이 주어진다. N은 100이하이다. 다음으로 N개의 수가 주어지는데 수는 1,000 이하의 자연수이다.
주어진 수들 중 소수의 개수를 출력한다.
4
1 3 5 7
3
import java.io.*;
import java.util.*;
public class Main{
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int totalNum = 0;
int N = 0;
for(int i = 0; i < T; i++){
N = Integer.parseInt(st.nextToken());
int K = 0;
if(N != 1){
for(int j = 1; j <= N; j++){
if(N % j == 0){
K++;
}
}
if(K <= 2){
totalNum++;
}
}
}
System.out.println(totalNum);
}
}
while(st.hasMoreTokens()) {
// 소수인경우 true, 아닌경우 false
boolean isPrime = true;
int num = Integer.parseInt(st.nextToken());
if(num == 1) {
continue;
}
for(int i = 2; i <= Math.sqrt(num); i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
count++;
}
}
Math.sqrt(num)
: 제곱근 구하기https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity
public class Eratos {
public static void main(String[] args) {
// ArrayList로 구현
ArrayList<Boolean> primeList;
// 사용자로부터의 콘솔 입력
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
// n <= 1 일 때 종료
if(n <= 1) return;
// n+1만큼 할당
primeList = new ArrayList<Boolean>(n+1);
// 0번째와 1번째를 소수 아님으로 처리
primeList.add(false);
primeList.add(false);
// 2~ n까지 소수로 설정
for(int i=2; i<=n; i++ )
primeList.add(i, true);
// 2부터 ~ i*i <= n
// 각각의 배수들을 지워간다.
for(int i=2; (i*i)<=n; i++){
if(primeList.get(i)){
for(int j = i*i; j<=n; j+=i) primeList.set(j, false);
//i*i 미만은 이미 처리되었으므로 j의 시작값은 i*i로 최적화할 수 있다.
}
}
StringBuffer sb = new StringBuffer();
sb.append("{");
for(int i=0; i<=n; i++){
if(primeList.get(i) == true){
sb.append(i);
sb.append(",");
}
}
sb.setCharAt(sb.length()-1, '}');
System.out.println(sb.toString());
}
}