본문 바로가기
알고리즘/프로그래머스

[프로그래머스] 소수 찾기(Java)

by hxxyeoniii 2025. 2. 24.

링크 : https://school.programmers.co.kr/learn/courses/30/lessons/42839#qna

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


문제 풀이

import java.util.*;

class Solution {
    static HashSet<Integer> set = new HashSet<>();
    static boolean[] visited = new boolean[7]; // 1 이상 7 이하 문자열
    
    public int solution(String numbers) {
        DFS("", numbers, 0);
        return set.size();
    }
    
    public void DFS(String str, String numbers, int depth) {
        
         if(depth > numbers.length()) {
            return;
         }
        
        for(int i=0; i<numbers.length(); i++) {
            if(!visited[i]) {
                visited[i] = true;
                if(isPrime(str + numbers.charAt(i))) {
                    set.add(Integer.parseInt(str + numbers.charAt(i)));
                }
                DFS(str + numbers.charAt(i), numbers, depth + 1);
                visited[i] = false;
              }
           }
	}
    
    // 소수 판별
    public boolean isPrime(String numStr) {
        int num = Integer.parseInt(numStr);
        
		if(num < 2) {
			return false;
		}

		for(int i=2; i<=Math.sqrt(num); i++) {
			if(num % i == 0) {
				return false;
			}
		}
        
		return true;
	}
}

 

 

 

DFS 주의할 점...