내가 쓴 답안
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testCase = scanner.nextInt();
int[] numberList = new int[testCase];
for(int i = 0; i< testCase ; i++) {
numberList[i] = scanner.nextInt();
}
int count = 0;
for(int j = 0; j < numberList.length; j++) {
int trueOrFalse= isPrime(numberList[j]);
if(trueOrFalse == 1) {
count++;
}
}
System.out.println(count);
}
public static int isPrime(int n) {
if(n == 1) {
return 0;
}
for (int i = 2; i<=(int)Math.sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
}
소수(prime number)란?
1보다 큰 자연수 중 1과 자기 자신만을 약수로 가지는 수다.
예) 2, 3, 5, 7, 11 ...
Math.sqrt()
제곱근(루트, squre root) 구하는 메소드.
java.lang.Math 클래스의 sqrt()메소드를 사용.
java.lang.Math 클래스는 수학 계산에 사용할 수 있는 메소드를 제공.
Math 클래스가 제공하는 메소드는 모두 정적이므로 import나 Math클래스 선언 없이 바로 사용이 가능하다.
반복문의 범위가 2부터 루트n까지인 이유
소수는 1과 자기 자신으로만 나누어지는 숫자이기 때문에.