Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 21278
- Eclipse
- docker
- 설정
- SpringBoot
- 이산수학
- 18222
- dockercompose
- Error
- 별자리 만들기
- 백준
- 프로그래머스
- 알고리즘
- 호석이두마리치킨
- jenkins
- 소가길을건너간이유6
- 20055
- EC2
- Error fetching remote repo 'origin'
- Java
- 날짜일수
- 투에모스문자열
- CMD
- documentationpluginsbootstrapper
- 2167. 2차원 배열의 합
- to display the conditions report re-run your application with 'debug' enabled
- 2108_통계학
- 이클립스
- 자바
- 14466
Archives
- Today
- Total
계단을 오르듯이
[JAVA] 소수 찾기(완전탐색) 본문
소수 찾기에서 2부터 시작하여 해당 num의 루트 Math.sqrt(num)까지를 포함해 구하였다.
HashSet 자료구조를 이용해 개수를 구하였다.
import java.util.*;
class Solution {
static Set<Integer> set = new HashSet<>();
public int solution(String numbers) {
int answer = 0;
int len = numbers.length();
boolean[] visited = new boolean[len];
int[] choice = new int[len];
for(int i=1;i<=len;i++){ // 선택 수
perm(0,i,numbers,visited,choice);
}
answer = set.size();
return answer;
}
// 소수인지 판별
private static boolean isOK(int n){
if(n < 2) return false;
for(int i=2;i<=Math.sqrt(n);i++){
if(n%i == 0) return false;
}
return true;
}
// 순열
private static void perm(int cnt, int limit, String numbers, boolean[] visited, int[] choice){
if(cnt == limit){
String str = "";
for(int i=0;i<limit;i++){
str += choice[i]+"";
}
if(isOK(Integer.parseInt(str))) { // 소수
System.out.println(Integer.parseInt(str));
set.add(Integer.parseInt(str));
}
return;
}
for(int i=0;i<numbers.length();i++){
if(visited[i]) continue;
visited[i] = true;
choice[cnt] = numbers.charAt(i)-'0';
perm(cnt+1, limit, numbers, visited, choice);
visited[i] = false;
}
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[JAVA] 네트워크 (0) | 2022.01.08 |
---|---|
[JAVA] 타겟 넘버 (0) | 2022.01.08 |
[JAVA] 가장 큰 수 (0) | 2022.01.07 |
[JAVA] 기능 개발 (0) | 2022.01.07 |
[JAVA] 위장 (0) | 2022.01.07 |