카테고리 없음

백준 2023번 신기한 소수 (JAVA)

박카스마시며코딩 2024. 1. 18. 21:30

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

 

2023번: 신기한 소수

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

www.acmicpc.net

 

저는 dfs를 통해 풀었습니다.

dfs를 통해 해당하는 자리 수의 모든 수가 문제 조건에 맞는 소수인지를 판단하여 풀었습니다.

 

package BOJ.etc;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class BOJ_2023_2 {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        cal(0,0,n);
    }
    private static void cal(int depth, int num, int n) {
        if(depth == n){
            System.out.println(num);
            return ;
        }
        for(int i = 0 ; i < 10 ; i++){
            if(depth == 0 && i == 0){
                continue;
            }
            int next = 10*num+i;
            if (isPrime(next)) {
                cal(depth+1,10*num + i,n);
            }
        }
    }
    private static boolean isPrime(int number){
        if(number == 1){
            return false;
        }
        if(number == 2){
            return true;
        }
        for(int i = 2; i <= Math.sqrt(number); i++){
            if(number % i == 0){
                return false;
            }
        }
        return true;
    }

}