프로그래머스 소수 찾기 자바

2023. 5. 8. 02:12코딩테스트/프로그래머스

https://school.programmers.co.kr/learn/courses/30/lessons/42839

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

이 문제의 전략은

 

1. 가능한 조합을 구한다.

2. 소수 판별

3. 소수 개수 구하기

 

import java.util.HashSet;
import java.util.Iterator;

public class Solution42839 {

    HashSet<Integer> numberSet = new HashSet<>();

    // 모든 조합 구하기
    public void combination(String str, String others) {

        if (!str.equals(""))
            numberSet.add(Integer.valueOf(str));

        for (int i = 0; i < others.length(); i++)
            combination(str + others.charAt(i), others.substring(0, i) + others.substring(i + 1));
    }

    // 소수 판별
    public boolean isPrime(int number) {

        if (number == 0 || number == 1)
            return false;

        int limit = (int) Math.sqrt(number);

        for (int i = 2; i <= limit; i++) {
            if (number % i == 0)
                return false;
        }

        return true;
    }

    public int solution(String numbers) {
        int count = 0;
        combination("", numbers);

        Iterator<Integer> it = numberSet.iterator();

        while (it.hasNext()) {
            int number = it.next();

            if (isPrime(number))
                count++;
        }

        return count;
    }

    public static void main(String[] args) {

        Solution42839 s = new Solution42839();
        String numbers = "17";

        int result = s.solution(numbers);
        System.out.println(result);
    }
}