[프로그래머스][JAVA] 소수 찾기 (완전 탐색, 소수)

2022. 3. 25. 00:03· 알고리즘 풀이/프로그래머스
728x90

220607

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.*;
 
class Solution {
    public int solution(String numbers) {
        int answer = 0;
        Set<Integer> set = new HashSet<>();
        permutation("", numbers, set);
        while(set.iterator().hasNext()){
            int a = set.iterator().next();
            set.remove(a);
            if(isPrime(a)){
                answer++;
            }
        }
        
        
        
        return answer;
    }
    private boolean isPrime(int n){
        if(n==2) return true;
        if(n==0 || n==1 || n%2==0){
            return false;
        }
        for(int i=3; i<=(int)Math.sqrt(n); i+=2){
            if(n%i==0) return false;
        }
        return true;   
    }
    
    private void permutation(String prefix, String str, Set set){
        int n = str.length();
        if(!prefix.equals("")) set.add(Integer.valueOf(prefix));
        for(int i=0; i<n; i++){
            permutation(prefix+str.charAt(i), str.substring(0,i)
                +str.substring(i+1,n), set);
        }
        
    }
}
Colored by Color Scripter
cs

 

 

 

숫자 num의 소수 구하기는 (int)Math.sqrt(num)까지만 하면 된다

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.*;
 
class Solution {
    private static boolean[] isVisited;
    private static Set<Integer> set;
    
    public int solution(String numbers) {
        int[] arr = Arrays.stream(numbers.split(""))                     
                        .mapToInt(Integer::parseInt).toArray();   
        isVisited = new boolean[arr.length];
        set = new HashSet<>();
        
        permutation(arr);
        int answer = 0;
        // set.forEach(System.out::println);
        for(Integer i : set){
            if(isPrimeNum(i)) answer++;
        }
         
        return answer;
    }
    
    private boolean isPrimeNum(int num){
        if(num==0 || num==1) return false;
        
        for(int i=2; i<=(int)Math.sqrt(num); i++){
            if(num%i==0) return false;
        }
        
        return true;
    }
    
    private void permutation(int[] arr){
        for(int i=1; i<=arr.length; i++){
            permutation(arr, new StringBuilder(), 0,i);
        }
    }
    
    private void permutation(int[] arr, StringBuilder sb, 
                                        int depth,int count){
        if(depth == count){
            // System.out.println(sb.toString());
            set.add(Integer.parseInt(sb.toString()));
            return;
        }
        for(int i=0; i<arr.length; i++){
            if(!isVisited[i]){
                isVisited[i] = true;
                permutation(arr, sb.append(arr[i]), depth+1, count);
                sb.deleteCharAt(sb.length()-1);
                isVisited[i] = false;     
            }
        }
        
    }
    
    
// 에라토스테네스의 체를 미리 만들어놓은 다음에 풀려고 했는데 
// 택도 없음 n의 Math.sqrt(n)를 활용해서 구해야 시간에서 안터짐
//     private boolean[] getPrimeNumArr(int max){
//         boolean[] isPrimeNum = new boolean[max+1];
//         for(int i=2; i<=max; i+=2){
//             isPrimeNum[i]=true;
//         }
//         for(int i=2; i<=max; i++){
//             if(!isPrimeNum[i] && checkPrime(i)){
//                 for(int j=i; j<=max; j+=i){
//                     isPrimeNum[i]=true;
//                 }
//             }
//         }
        
//         return isPrimeNum;
//     }
    
//     private boolean checkPrime(int num){
//         for(int i=2; i<num; i++){
//             if(num%i==0) return true;
//         }
//         return false;
//     }
}
Colored by Color Scripter
cs
저작자표시 (새창열림)

'알고리즘 풀이 > 프로그래머스' 카테고리의 다른 글

[프로그래머스][JAVA] 게임 맵 최단거리 (BFS(o), DFS(x))  (0) 2022.03.25
[프로그래머스][JAVA] 조이스틱 (완전탐색/ 그리디...?)  (0) 2022.03.25
[프로그래머스][JAVA] 가장 큰 수 (문자열, 정렬)  (0) 2022.03.24
1 ★★★ [프로그래머스][JAVA] 전화번호 목록 (문자열)  (0) 2022.03.24
1 ★★★ [프로그래머스][JAVA] 빛의 경로 사이클 (배열, 구현..?, 재귀를 while문으로)  (0) 2022.03.24
'알고리즘 풀이/프로그래머스' 카테고리의 다른 글
  • [프로그래머스][JAVA] 게임 맵 최단거리 (BFS(o), DFS(x))
  • [프로그래머스][JAVA] 조이스틱 (완전탐색/ 그리디...?)
  • [프로그래머스][JAVA] 가장 큰 수 (문자열, 정렬)
  • 1 ★★★ [프로그래머스][JAVA] 전화번호 목록 (문자열)
배게
배게
백엔드배게 님의 블로그입니다.
배게
백엔드
배게
전체
오늘
어제
  • 분류 전체보기 (430)
    • 알고리즘 풀이 (338)
      • 백준 (167)
      • Codility (22)
      • 프로그래머스 (123)
      • LeetCode (2)
      • CodeForces (9)
      • SWEA (15)
    • 백엔드 (11)
    • Coding existing for (3)
    • 무지성 메모 (40)
    • Debug (30)
    • 자바 (8)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • hibernate
  • 카톡
  • 카카오톡
  • 카카오톡 txt파일 정렬
  • 카톡 내보내기한 파일 정렬
  • MYSQL

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.1
배게
[프로그래머스][JAVA] 소수 찾기 (완전 탐색, 소수)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.