문제 설명

주어진 자연수 n이 1과 자기 자신으로만 나누어지는 여부를 출력하는 프로그램을 구현하세요.


입력 형식

· n : 주어진 자연수 (정수)


출력 형식

·  조건에 맞는지 여부를 논리값으로 반환


제약 사항

· 1 < n <= 100000000


입출력 예시

· 입력

      · n = 7

· 출력 : true

· 설명 : 7은 소수이므로 1과 자기자신만으로 나누어진다.


작성 코드

class Solution {
    public boolean solution(int n) {
        boolean answer = true;
        int count = 0;

        for (int i = 2; i < n; i++) {
            if(n % i == 0) {
                count++;
            }
        }
        if (count >= 1) {
            answer = false;
        }
        return answer;
    }

    public static void main(String[] args) {
        Solution st = new Solution();
        int n = 7;
        System.out.println(st.solution(n));
    }
}

 

정답 코드

class Solution {
    public boolean solution(int n) {
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Solution st = new Solution();
        int n = 7;
        System.out.println(st.solution(n));
    }
}