본문 바로가기

알고리즘/백준

[백준] 1978 - 소수 찾기 (JAVA/ 자바)

반응형

1978번 문제

 

 

1. Scanner를 이용한 방법

import java.util.Scanner;

public class Main{
public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int num = 0;
    int count = 0;
    for(int i=0; i<N; i++){
        num = sc.nextInt();
        
        for(int j=2; j<=num; j++){
            if(j == num){
                count++;
            }
            if(num % j == 0){
                break;
            }
        }
    }
    System.out.print(count);
    sc.close();
    }
}

 

2.BufferedReader를 이용한 방법

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

public class Main{
public static void main(String[] args)throws IOException{

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(br.readLine());
    int num = 0;
    int count = 0;
    StringTokenizer st = new StringTokenizer(br.readLine(), " ");
    for(int i=0; i<N; i++){
        num = Integer.parseInt(st.nextToken());
        for(int j=2; j<=num; j++){
            if(j == num){
                count++;
            }
            if(num % j == 0){
                break;
            }
        }
    }
    System.out.print(count);
    br.close();
    }
}
반응형