정답
import java.util.*;
import java.lang.*;
class Solution {
public int solution(int[] nums) {
int count = 0;
//3개의 수를 더했을 때 소수가 되는 경우의 수
//3개를 골라 소수가 되는 경우의 수
int length = nums.length;
int number = 0;
for(int i=0; i<length; i++){
for(int j=i+1; j<length; j++){
for(int k=j+1; k<length; k++){
number = nums[i] + nums[j] + nums[k];
if(prime(number)){
count++;
}
}
}
}
return count;
}
private boolean prime(int number){//소수인지 판단하는 함수
if(number <= 1){
return false;
}
double numberSqrt = Math.sqrt((double)number);
int numberSqrtRound = (int) Math.round(numberSqrt);
Integer[] divisorArr = divisor(number);
for(int divisor : divisorArr){
if(divisor != 1){
for(int i=2; i <= numberSqrtRound; i++){
if(divisor == i){ //약수가 있는 경우
return false;
}
}
}
}
return true;
}
private Integer[] divisor(int number){
List<Integer> divisorList = new ArrayList<>();
for(int i = 1; i<=number; i++){
if(number % i == 0){
divisorList.add(i);
}
}
return divisorList.stream().toArray(Integer[]::new);
}
}
분석
- 소수 판단을 조금 더 간편하게 하는 풀이가 있음
import java.util.Arrays;
class Solution {
public int solution(int[] nums) {
int ans = 0;
for(int i = 0; i < nums.length - 2; i ++){
for(int j = i + 1; j < nums.length - 1; j ++){
for(int k = j + 1; k < nums.length; k ++ ){
if(isPrime(nums[i] + nums[j] + nums[k])){
ans += 1;
}
}
}
}
return ans;
}
public Boolean isPrime(int num){
int cnt = 0;
for(int i = 1; i <= (int)Math.sqrt(num); i ++){
if(num % i == 0) {
cnt += 1;
}
}
return cnt == 1;
}
}