본문 바로가기

프로그래머스/완전탐색

소수찾기

728x90

문제 설명

한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.

각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.

제한사항

  • numbers는 길이 1 이상 7 이하인 문자열입니다.
  • numbers는 0~9까지 숫자만으로 이루어져 있습니다.
  • 013은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.

입출력 예

numbersreturn

numbers return
17 3
011 2

입출력 예 설명

예제 #1
[1, 7]으로는 소수 [7, 17, 71]를 만들 수 있습니다.

예제 #2
[0, 1, 1]으로는 소수 [11, 101]를 만들 수 있습니다.

  • 11과 011은 같은 숫자로 취급합니다.

 

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <map>
#include <math.h>
using namespace std;

bool findsosu(int num){
    if(num ==0 || num==1){return false;}
    for(int i=2; i<=sqrt(num);i++){
        if(num%i==0){return false;}
    }
    return true;
}

int solution(string numbers) {
    int answer = 0;
    int n = numbers.size();
    map<int,bool>m;
    string copynumbers=numbers;
    for(int i=1; i<=numbers.size();i++){
        vector<int>check(n,0);
        int k = i;
        int idx =0;
        while(k!=0){
            check[idx]=1;
            k--;
            idx++;
        }
   sort(copynumbers.begin(),copynumbers.end());
   do{
        string str="";
        for(int i=0; i<n; i++){
            
            if(check[i]==1){
                str+=copynumbers[i];
            }
        }

        int num = stoi(str);
        if(findsosu(num)==true){
            if(m[num]==false){
                answer++;m[num]=true;
            
            }
        }
    }while(next_permutation(copynumbers.begin(), copynumbers.end()));
    }
    return answer;
}

'프로그래머스 > 완전탐색' 카테고리의 다른 글

단체사진 찍기  (0) 2021.01.15
점프와 순간이동  (0) 2021.01.05
카펫  (0) 2021.01.05
소수 만들기  (0) 2021.01.04
Level1 - 모의고사 (C++)  (0) 2020.10.14