Search
Duplicate
📒

[Programmers] 09-1. k 진수에서 소수 개수 구하기

상태
완료
수업
Algorithm Solving
주제
Programmers
4 more properties
참고

문제해설

NOTE
입력값 ⇒ 정수값 n, 정수값 k
출력값 ⇒ n의 정수를 k진법으로 변경했을때 조건에 맞는 숫자가 몇개가 나오는

문제 로직고민

NOTE
숫자 n을 k진법으로 변경한다음 0을 기준으로 숫자를 모두 구분한다.
조건의 숫자는 0을 포함하지 않다고 명시되어 있다.

작성코드

NOTE
class Solution { public int solution(int n, int k) { int answer = 0; // 10진법 -> n진법은 toString으로 간단하게 변환가 String[] split = Integer.toString(n, k).split("0"); // String temp = Integer.parseInt(n, 5) 이렇게 n -> 10진법도 쉽게 가 for(String sp : split){ if(sp.equals("")) continue; Long temp = Long.parseLong(sp); if(prime(temp)) answer++; } return answer; } private boolean prime(Long n){ if(n == 1) return false; // 여기서 ceil을 사용했다가 30분소모... long limit = (long) Math.floor(Math.sqrt(n)); for(long i=2; i<=limit; i++){ if(n % i == 0) return false; } return true; } }
Java
복사

다른사람 풀이

NOTE
class Solution { public int solution(int n, int k) { int ans = 0; String temp[] = Integer.toString(n, k).split("0"); Loop : for(String t : temp) { if(t.length() == 0) continue; long a = Long.parseLong(t); if(a == 1) continue; for(int i=2; i<=Math.sqrt(a); i++) if(a%i == 0) continue Loop; ans++; } return ans; } }
Java
복사
제일 깔끔한 코