백준 1978번 (복습)

김경욱·2026년 1월 24일

백준

목록 보기
116/121

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

// Press Shift twice to open the Search Everywhere dialog and type show whitespaces,
// then press Enter. You can now see whitespace characters in your code.
public class Main {
public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int x = Integer.parseInt(br.readLine());
    StringTokenizer st = new StringTokenizer(br.readLine());

    int[] arr = new int[x];
    int count = 0;

    boolean is = false;
    for (int i = 0; i < arr.length; i++) {
        arr[i] = Integer.parseInt(st.nextToken());
        if(isValid(arr[i]))
        {
            count++;
        }
    }
    System.out.println(count);










}

public static boolean isValid(int x) {

    if (x < 2) {
        return false;
    }
    if(x==2) {
        return true;
    }
    if(x % 2 ==0 ){
        return false;
    }

    for (int j = 3; j * j <=x; j +=2)
    {
        if (x %j ==0)
        {
            return false;
        }
    }

        return true;
}

}

소수를 구하는 메서드를 까먹어서 어려웠다 !
2보다 작을때,
2일때,
2로 나누어떨어질때,
3이상일 경우에는 범위를 j * j <= x로 정하고 j를 한개씩 아닌 2개씩 올린다.
그 이유는 홀수는 절대로 짝수로 나누어 떨어지지 않고, 계산을 효율적이게 하기 위해서이다.

0개의 댓글