728x90
[Gold V] 신기한 소수 - 2023
성능 요약
메모리: 12856 KB, 시간: 108 ms
분류
백트래킹(backtracking), 수학(math), 정수론(number_theory), 소수 판정(primality_test)
문제 설명
수빈이가 세상에서 가장 좋아하는 것은 소수이고, 취미는 소수를 가지고 노는 것이다. 요즘 수빈이가 가장 관심있어 하는 소수는 7331이다.
7331은 소수인데, 신기하게도 733도 소수이고, 73도 소수이고, 7도 소수이다. 즉, 왼쪽부터 1자리, 2자리, 3자리, 4자리 수 모두 소수이다! 수빈이는 이런 숫자를 신기한 소수라고 이름 붙였다.
수빈이는 N자리의 숫자 중에서 어떤 수들이 신기한 소수인지 궁금해졌다. N이 주어졌을 때, 수빈이를 위해 N자리 신기한 소수를 모두 찾아보자.
입력
첫째 줄에 N(1 ≤ N ≤ 8)이 주어진다.
출력
N자리 수 중에서 신기한 소수를 오름차순으로 정렬해서 한 줄에 하나씩 출력한다.
풀이
처음에는 문제 조건의 4MB를 고려하지 못해서 에라토스테네스의 체를 써서 10^8까지 소수를 구해놓고, 수를 하나씩 검증하려고 했다.
그래서 배열에 미리 저장하지 않고 재귀를 사용해서 경우의 수를 줄이는 방법을 선택했다.
한 자리 수일 때는 2, 3, 5, 7이 소수이고, 2, 3, 5, 7로 시작하는 두 자리 소수의 경우도 많지 않으니 이런 방식으로 소수를 구해 나가면 시간도, 메모리도 효율적이다.
소수를 구하는 문제라고 에라토스테네스의 체만 생각하다가 가장 기본적인 소수를 판별하는 방법을 사용할 생각을 못 했다.
package BOJ.Gold.g5;
import java.util.Scanner;
public class BOJ_2023_신기한소수 {
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
dfs(0, N);
System.out.print(sb);
}
static void dfs(int num, int length) {
if (length == 0) {
if (isPrime(num)) sb.append(num).append("\n");
return;
}
for (int i = 1; i < 10; i++) {
int newNum = num * 10 + i;
if (isPrime(newNum)) dfs(newNum, length - 1);
}
}
static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}
}
728x90
'Java' 카테고리의 다른 글
[백준] 10986 - 나머지 합 (자바/Java) (0) | 2022.09.27 |
---|---|
[자바/Java] 예외 처리 (Exception) (0) | 2022.07.28 |
[자바/Java] 직렬화와 역직렬화, ObjectInputStream ObjectOutputStream, Serializable (0) | 2022.07.28 |
[자바/Java] 객체 참조 시 인터페이스 사용 이유 (0) | 2022.07.28 |
[자바/Java] 제네릭 Generics (0) | 2022.07.27 |