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

Gaanii·2025년 5월 14일
0

Problem Solving

목록 보기
197/210
post-thumbnail

아래 프로그래머스 로고를 클릭하면 해당 문제로 이동합니다 😀

프로그래머스로고



풀이과정


진법 변환 문제가 자주나오네용 ?

이 문제의 풀이 흐름은 다음과 같습니다!
1. nk진수 문자열로 변환 -> convert_Num, toString() 이용
2. "0"을 기준으로 split해서 후보 문자열 배열을 생성
3. 각 후보 문자열이 비어있지 않고, 10진수(int)로 읽었을 때 소수인지 검사
4. 소수라면 결과값 증가

이렇게 하면 "0P0", "P0", "0P", "P" 형태를 모두 체크할 수 있다.

정규표현식으로도 풀 수 있지 않을까 ? 했는데 머리가 살짝쿵 아파서 오늘은 pass ..

코드


1. Python

py에선 진법 변환을 직접 해야한다 ,, convert_Num 참고 !

def is_Prime(n):
    if n <= 2 or n % 2 == 0:
        return n == 2
    for i in range(3, int(n ** 0.5) + 1, 2):
        if n % i == 0:
            return False
    return True
    
def convert_Num(n, k):
    convert_num = ""
    while n > 0:
        convert_num = str(n % k) + convert_num
        n //= k
    return convert_num
    
def solution(n, k):
    candidates = convert_Num(n, k).split("0")
    
    result = 0
    for cand in candidates:
        if cand and is_Prime(int(cand)):
            result += 1
    return result

2. JS

js에서는 toString을 이용하자 !

function isPrime(n){
    if (n < 2 || n % 2 === 0) return n === 2;
    for(let i = 3; i < Math.floor(n ** 0.5) + 1 ; i += 2){
        if(n % i == 0) return false;
    }
    return true;
}

function solution(n, k) {
    const convertNum = n.toString(k);
    const candidates = convertNum.split("0");
    
    let result = 0;
    for(const cand of candidates){
        if(isPrime(+cand)) result++;
    }
    return result;
}


결과


정답

0개의 댓글