Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
more
Archives
Today
Total
관리 메뉴

코딩응급실

프로그래머스: k진수에서 소수 개수 구하기 본문

Java

프로그래머스: k진수에서 소수 개수 구하기

Daeryuk Kim 2024. 3. 17. 21:30
import java.util.*;

class Solution {
    public int solution(int n, int k) {
        // n을 k진수로 변환
        String kBaseNum = Integer.toString(n, k);
        
        // 변환된 수에서 조건에 맞는 소수 찾기
        int count = 0;
        String[] candidates = kBaseNum.split("0"); // 0을 기준으로 나눔
        
        for (String candidate : candidates) {
            if (!candidate.isEmpty() && isPrime(Long.parseLong(candidate))) {
                count++;
            }
        }
        
        return count;
    }

    // 소수 판별 함수
    private boolean isPrime(long num) {
        if (num < 2) return false;
        for (long i = 2; i * i <= num; i++) {
            if (num % i == 0) return false;
        }
        return true;
    }
    public static void main(String[] args) {
        int n = 437674;
        int k = 3;
        
        Solution sol = new Solution();
        int result = sol.solution(n, k);
        System.out.println(result);
        
    }
}