본문 바로가기
알고리즘/알고리즘

[C++] 프로그래머스 : 소수찾기

by 두둠칫 2022. 3. 10.

 - 소수판별 알고리즘

 - set 활용법 : iterator, insert

 - string에도 begin(), end()

 - next_permutation : 순열정렬 라이브러리 함수  *적용전 배열 sort 필요

#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <cmath>

using namespace std;

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

int solution(string numbers) {
    int answer = 0;
    
    string num = numbers;
	sort(num.begin(), num.end());
    int nSize = num.length();
    
    set<int> sn;
    
    int tmp;
    do{
        for(int i=1; i<=nSize; i++){
            tmp = stoi(num.substr(0, i));
            sn.insert(tmp);
        }
    }while(next_permutation(num.begin(), num.end()));
    
    for(set<int>::iterator it = sn.begin(); it != sn.end(); it++){
        if(isPrime(*it))
            answer++;
    }
    
    return answer;
}