[Programmers] 소수 찾기

Time Lapse :20min 0sec

solution.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <string>
#include <vector>
#include <math.h>
using namespace std;
//20:00
int number[10]={0,};
int answer = 0,size;
int cur_size;
void calc(int d,int &s,vector<bool> &Primes){
if(d==cur_size){
if((s&1)&Primes[s/2])
++answer;
return ;
}
for(int i=0;i<=9;i++){
if(number[i]!=0){
--number[i]; s = s * 10 + i;
calc(d + 1, s, Primes);
++number[i]; s /= 10;
}
}
}

int solution(string numbers) {
size = numbers.length();
int MAXLEN = pow(10,size);
vector<bool> Primes(MAXLEN/2,true);
for(int i=0;i<size;i++)
++number[numbers[i]-48];

Primes[0] = false;
for(long long i=3;i*i<MAXLEN;i+=2){
if(!Primes[i/2])
continue;
for(long long j=i*i;j<MAXLEN;j+=i*2)
Primes[j/2] = false;
}
if(number[2]>0)
++answer;
for(cur_size=1;cur_size<=size;cur_size++)
for (int i = 1; i <= 9; i++)
if (number[i] != 0) {
--number[i];
calc(1, i, Primes);
++number[i];
}
return answer;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/30/PS/Programmers/searchPrimeNumber/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.