[Java] 백준 1978번: 소수 찾기

U·2023년 3월 17일

백준

목록 보기
26/116

💻 문제


일단 이해하자🤔

  • 소수가 무엇인지 이해하면 풀기 쉬운 문제다. 소수란 1과 자기 자신 말고는 약수가 없는 수다. 예를 들면 3, 5, 7이 있는데 이때 1은 소수에 해당하지 않는다. 그래서 예제에서 소수의 개수가 3인 것이다.
  • 소수인지 아닌지 판별하기 위한 boolean형 변수 decimalfalse로 선언해두고 1과 자기 자신을 뺀 다른 수로 나누어지는 수는 false가 되도록 하면 된다. 그리고 for문을 벗어나게 해서 count에 해당되지 않도록 했으며 마지막엔 소수를 센 count의 수를 출력하면 끝!

👀 풀이

import java.io.*;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(System.out));

        int N = Integer.parseInt(bfr.readLine());

        String str = bfr.readLine();
        StringTokenizer st = new StringTokenizer(str, " ");
        int count = 0;
        boolean decimal = false;

        for (int i = 0; i < N; i++) {
            int num = Integer.parseInt(st.nextToken());

            if (num > 1) {
                for (int j = 2; j <= num; j++) {
                    if (num % j == 0 && num != j) {
                        decimal = false;
                        break;
                    }
                    else {
                        decimal = true;
                    }
                }

                if (decimal) {
                    count++;
                }
            }
        }

        bfw.write(String.valueOf(count));
        bfr.close();
        bfw.flush();
        bfw.close();
    }
}

💡 결과

profile
백엔드 개발자 연습생

0개의 댓글