본문 바로가기
백준 알고리즘 자바

1978번

by leko 2023. 7. 6.

나의 코드

package boj;

import java.util.Scanner;

public class BOJ_1978 {

	private static int sosu;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//소수의 특징 : 2 3 5 7  11
		// 1부터 소수까지 숫자들중에서 1과 자기자신을 제외하고는 나누어 떨어지지않는다!
		
		Scanner sc = new Scanner(System.in);
		int cnt = sc.nextInt();
		int ans = 0;
		int arr[] =  new int[cnt];
		for(int i=0;i<cnt ;i++){
			arr[i] = sc.nextInt();
		}
		for(int i=0;i<cnt;i++){
			sosu = 0; //초기화 중요
			for(int j=1;j<arr[i];j++) {
				
				if((arr[i]/j==0&&arr[i]%j==1 ) || arr[i]%j==0) { // 1인경우 || 2~arr[i]-1까지는 절대 나머지 값이 0이 될 수 없음
					 sosu++;
				}
				
			}
			if(sosu==1) {
				ans++;
			}
			
		}
		System.out.println(ans);

	}

}

다른 사람 코드 참고

package boj;

import java.util.Scanner;

public class BOJ_1978Re {


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//소수의 특징 : 2 3 5 7  11
		// 1부터 소수까지 숫자들중에서 1과 자기자신을 제외하고는 나누어 떨어지지않는다!
		
		Scanner sc = new Scanner(System.in);
		int cnt = sc.nextInt();
		int ans = 0;
		
		for(int i=0;i<cnt;i++){
			boolean isPrime = true;
			int num = sc.nextInt();
			if(num == 1) { //num 이 1이면 for 문으로 가기
				//왜냐하면 1이 소수조건이 if(isPrime)조건을 만족하는것은 오류가 되기때문
				continue;
			}
			for(int j=2;j<= Math.sqrt(num);j++) { //num 이 2인경우는 이 조건에 들어가지도않음 // num이 4일때부터가능
				if(num %j==0) {
					isPrime = false;
					break;
				}	
			}
			if(isPrime) { 
				ans++;
			}
			
		}
		System.out.println(ans);

	}

}

'백준 알고리즘 자바' 카테고리의 다른 글

3085번  (0) 2023.07.07
17427번  (0) 2023.07.06
2309번  (0) 2023.07.06
1929번  (0) 2023.07.06
1037번  (0) 2023.06.27