알고리즘/완전탐색

프로그래머스 - Lv2 소수찾기(Java)

연향동큰손 2025. 1. 19. 16:09

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

 

프로그래머스

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

programmers.co.kr

 

이 문제에서 가장 어려웠던 부분은 입력된 문자열로 만들 수 있는 숫자를 모두 구하는 것 이다.

 

처음에 dfs 방식을 사용하면 되겠다고 생각을 했는데 dfs를 공부한지 오래되서 다른 풀이를 참고하면서 공부했다.

 

import java.util.*;

class Solution {
    static Set<Integer> set;
    static boolean[] visit = new boolean[7];
    
    public int solution(String numbers) {
        int answer = 0;
        set = new HashSet<>();
        int size = numbers.length();
        
        dfs(numbers,"",0);
        
        for(int num : set){
            if(check(num)){
                answer++;
            }
        }        
        return answer;
    }
    public static void dfs(String numbers, String s, int depth){
        if(depth>numbers.length()){
            return;
        }
        for(int i=0; i<numbers.length(); i++){
            if(!visit[i]){
                visit[i]=true;
                set.add(Integer.parseInt(s+numbers.charAt(i)));
                dfs(numbers,s+numbers.charAt(i),depth+1);
                visit[i]=false;
            }
        }
    }
    public static boolean check(int num){
        if(num<2){
            return false;
        }
        for(int i=2; i<num; i++){
            if(num%i==0){
                return false;
            }
        }
        return true;
    }
}

 

dfs를 통해 문자열에 있는 숫자들로 만들 수 있는 모든 숫자를 구하여 HashSet에 넣었다.

 

 dfs가 구현되는 과정을 아래 그림과 같다.

 


 

에라토스테네스의 체를 활용하여 성능 최적화

 

에라토스테네스의 체를 이용하면 소수 판별할때 반복횟수를 줄여서 실행시간을 줄일 수 있다.

 

입력 숫자 n이 소수인지를 판별할때는 루트n까지만 반복해주면 된다.

public static boolean check(int n){
        if(n<2){
            return false;
        }
        for(int i=2; i<=(int)Math.sqrt(n); i++){
            if(n%i==0){
                return false;
            }
        }
        
        return true;
    }