프로그래머스 LV1 - 소수만들기

J_C·2021년 6월 8일
0

소수만들기 Go

문제설명

주어진 숫자 중 3개의 수를 더했을 때 소수가 되는 경우의 개수를 구하려고 합니다. 숫자들이 들어있는 배열 nums가 매개변수로 주어질 때, nums에 있는 숫자들 중 서로 다른 3개를 골라 더했을 때 소수가 되는 경우의 개수를 return 하도록 solution 함수를 완성해주세요.

제한사항

nums에 들어있는 숫자의 개수는 3개 이상 50개 이하입니다.
nums의 각 원소는 1 이상 1,000 이하의 자연수이며, 중복된 숫자가 들어있지 않습니다.

생각을 해보자

소수를 판별하는 함수는 많이 짜봄
에라토스테네스의 체를 쓰든지 제곱근까지 포문돌리든지...

그럼 숫자 세개를 골라야하는데?
-> 세개 골라서 더하는거니까 조합이겠지?
-> 조합은 재귀써도되는데 3개밖에 더하는게 아니니까 그냥 삼중포문 Go!

내풀이

import java.util.*;

class Solution {
    public int solution(int[] nums) {
        int answer = 0;
        int sum = 0;
        for(int i = 0; i < nums.length;i++){
            for(int j = i+1; j < nums.length;j++){
                for(int k = j+1; k < nums.length;k++){
                    sum  =  nums[i] + nums[j] + nums[k];
                    if(isPrime(sum)){answer++;}
                }
            }
        }
        return answer;
    }
    public boolean isPrime(int n){
        for(int i = 2;i <= Math.sqrt(n);i++){
            if(n % i == 0){
                return false;
            }
        }
        return true;
    }
}

다른사람 풀이

나는 포문을 0~n / 1~n / 2~n 이런식으로 돌렸는데
0 ~ n-2 / 1 ~ n-1 / 2 ~ n 으로 해도됌
해도되는게 아니라 밑에 포문이 더 효율성 좋으니 저걸로 해야됌!!

조합 combination 재귀써도 가능!


    public static void combination(int[] arr, int index, int n, int r, int target, int[] nums) { 
        if (r == 0) 
            print(arr, index); 
        else if (target == n) 
            return; 
        else { 
            arr[index] = nums[target]; 
            combination(arr, index + 1, n, r - 1, target + 1, nums); 
            combination(arr, index, n, r, target + 1, nums); 
        } 
    }//end combination() 
profile
jiyeonsama

0개의 댓글