[BJ2023] 신기한 소수
✏️ 𝗔𝗹𝗴𝗼𝗿𝗶𝘁𝗵𝗺/백준 알고리즘

[BJ2023] 신기한 소수

 

 백준 - 신기한 소수 

문제 링크

https://www.acmicpc.net/problem/2023

 

2023번: 신기한 소수

수빈이가 세상에서 가장 좋아하는 것은 소수이고, 취미는 소수를 가지고 노는 것이다. 요즘 수빈이가 가장 관심있어 하는 소수는 7331이다. 7331은 소수인데, 신기하게도 733도 소수이고, 73도 소수

www.acmicpc.net

 

문제 입출력

4
2333
2339
2393
2399
2939
3119
3137
3733
3739
3793
3797
5939
7193
7331
7333
7393

 

문제 풀이

package day220805.practice;


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;


public class BJ2023_신기한소수 {
	static int N;
	static StringBuilder sb = new StringBuilder();


	// 소수인지 확인하는 메서드
	private static boolean isPrime(int n) {
		if (n == 1) return false;

		for (int i = 2; i * i <= n; i++) {
			if (n % i == 0) return false;
		}

		return true;

	}
	// end isPrime


	// 재귀
	private static void search(int idx, int n) {
		// 기저 조건
		// 인덱스가 N이 되면 끝
		if (idx == N) {
			sb.append(n + "\n");
			return;
		}

		// 짝수는 굳이 볼 필요가 없다.
		// 들어오는 n 을 String 으로 변경하여 끝에 1,3,5,9 을 붙이고
		// 소수인지 확인다.
		// 만약 소수라면 해당 숫자 다음 자릿수로 넘어간다.
		int nextNum = Integer.parseInt(Integer.toString(n) + 1);
		if (isPrime(nextNum)) search(idx + 1, nextNum);

		nextNum = Integer.parseInt(Integer.toString(n) + 3);
		if (isPrime(nextNum)) search(idx + 1, nextNum);

		nextNum = Integer.parseInt(Integer.toString(n) + 7);
		if (isPrime(nextNum)) search(idx + 1, nextNum);

		nextNum = Integer.parseInt(Integer.toString(n) + 9);
		if (isPrime(nextNum)) search(idx + 1, nextNum);

	}
	// end search


	public static void main(String[] args) throws Exception {
		System.setIn(new FileInputStream("input.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		N = Integer.parseInt(br.readLine());

		// 첫번째 자리에 소수를 넣고 시작한다.
		search(1, 2);
		search(1, 3);
		search(1, 5);
		search(1, 7);

		// 출력
		System.out.println(sb.toString());

	}
	// end main
}

 

 

 

 

 

 

 

 

 

 

# 백준 신기한 소수 java # BJ2023 java


 

728x90

'✏️ 𝗔𝗹𝗴𝗼𝗿𝗶𝘁𝗵𝗺 > 백준 알고리즘' 카테고리의 다른 글

[BJ2628] 종이 자르기  (0) 2022.08.09
[BJ12493] 탑  (0) 2022.08.08
[BJ12891] DNA 비밀번호  (0) 2022.08.08
[BJ21921] 블로그  (0) 2022.08.08
[BJ1244] 스위치 켜고 끄기  (0) 2022.08.01