https://www.acmicpc.net/problem/2023
2023번: 신기한 소수
수빈이가 세상에서 가장 좋아하는 것은 소수이고, 취미는 소수를 가지고 노는 것이다. 요즘 수빈이가 가장 관심있어 하는 소수 7331이다. 7331은 소수인데, 신기하게도 733도 소수이고, 73도 소수이고, 7도 소수이다. 즉, 왼쪽부터 1자리, 2자리, 3자리, 4자리 수 모두 소수이다! 수빈이는 이런 숫자를 신기한 소수라고 이름 붙였다. 수빈이는 N자리의 숫자 중에서 어떤 수들이 신기한 소수인지 궁금해졌다. N이 주어졌을 때, 수빈이를 위해 N자리 신
www.acmicpc.net
dfs로 문자열 뒤에 숫자를 붙여가면서 소수인지 체크해주었다.
소수인지 판별할 때 sqrt값을 사용하여 시간을 절약할 수 있었다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static int N;
public static boolean f;
public static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
dfs("", 0);
System.out.println(sb.toString());
}
private static void dfs(String s, int cnt) {
if (cnt == N) {
sb.append(s+'\n');
return;
}
for(int i=1; i<=9; i++) {
if(isPrime(Integer.parseInt(s+i))) {
dfs(s+i,cnt+1);
}
}
}
private static boolean isPrime(int num) {
if(num==1) return false;
int sqrt=(int)Math.sqrt(num);
for(int i=2; i<=sqrt; i++) {
if(num%i==0) return false;
}
return true;
}
}
'알고리즘 문제풀이 > 백준' 카테고리의 다른 글
[백준 2174] 로봇 시뮬레이션(JAVA) (2) | 2020.03.04 |
---|---|
[백준 1966] 프린터 큐(JAVA) (0) | 2020.03.04 |
[백준 1764] 듣보잡(JAVA) (0) | 2020.03.03 |
[백준 1389] 케빈 베이컨의 6단계 법칙(JAVA) (0) | 2020.03.01 |
[백준 14503] 로봇청소기(JAVA/C++) (1) | 2020.03.01 |
댓글