프로그래머스 소수찾기
2019. 10. 3. 16:32ㆍ알고리즘/프로그래머스
총 7자리이기 때문에 소수를 찾기 위해선 에라토스테네스의 체를 이용해야만 한다. NlgN만에 7자리까지 소수를 찾을 수 있기 때문이다. 그리고 순열과 완전탐색을 통해 모든 경우의 수를 찾은 후 정렬과 unique를 통해 중복을 삭제하도록 한다
문제: https://programmers.co.kr/learn/courses/30/lessons/42839
깃허브주소: https://github.com/surinoel/boj/blob/master/Programmers_소수찾기.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <string> | |
#include <cstring> | |
#include <algorithm> | |
using namespace std; | |
bool check[10000000]; | |
vector<int> totalset; | |
void go(int cnt, int num, const vector<int> &idx) { | |
if (cnt == idx.size()) { | |
if (num != 0) { | |
totalset.push_back(num); | |
} | |
return; | |
} | |
go(cnt + 1, num, idx); | |
if (!(num == 0 && idx[cnt] == 0)) { | |
go(cnt + 1, num * 10 + idx[cnt], idx); | |
} | |
return; | |
} | |
int solution(string numbers) { | |
string s = numbers; | |
vector<int> idx; | |
for (int i = 0; i < s.size(); i++) { | |
int num = s[i] - '0'; | |
idx.push_back(num); | |
} | |
sort(idx.begin(), idx.end()); | |
do { | |
go(0, 0, idx); | |
} while (next_permutation(idx.begin(), idx.end())); | |
sort(totalset.begin(), totalset.end()); | |
totalset.erase(unique(totalset.begin(), totalset.end()), totalset.end()); | |
memset(check, true, sizeof(check)); | |
check[1] = false; | |
for (int i = 2; i * i < 10000000; i++) { | |
if (!check[i]) continue; | |
for (int j = i + i; j < 10000000; j += i) { | |
check[j] = false; | |
} | |
} | |
int ans = 0; | |
for (int i = 0; i < totalset.size(); i++) { | |
if (check[totalset[i]]) { | |
ans += 1; | |
} | |
} | |
return ans; | |
} |
'알고리즘 > 프로그래머스' 카테고리의 다른 글
프로그래머스 체육복 (0) | 2019.10.08 |
---|---|
프로그래머스 카펫 (0) | 2019.10.03 |
프로그래머스 베스트앨범 (0) | 2019.09.22 |
프로그래머스 숫자야구 (0) | 2019.09.22 |
프로그래머스 라면공장 (0) | 2019.09.22 |